XAML Essentials Cheat Sheet
XAML Essentials Cheat Sheet
XAML vs Code-behind
Everything you do with XAML, can be done with code.
At run-time, XAML parser will process our XAML files and instantiate C# objects.
We should aim to use XAML for defining the visual appearance of our apps, and
use C# for implementing behaviour.
Handling Events
In XAML:
In code-behind:
Names
We use x:Name attribute to assign an identifier to an element. This will generate a
private field that we can access in code-behind or XAML:
1
XAML Essentials By: Mosh Hamedani
<ContentPage.Padding>
<OnPlatform x:TypeArguments=Thickness
iOS=0, 20, 0, 0
Android=0, 40, 0, 0 />
</ContentPage.Padding>
Content Property
Some XAML elements (eg ContentPage and StackLayout) have a content property.
That means, what we put between their start and end tags will be assigned to their
content property. And with this, we dont need to explicitly specify the content property.
So, instead of
<ContentPage>
<ContentPage.Content>
<Label />
</ContentPage.Content>
</ContentPage>
<ContentPage>
<Label />
</ContentPage>
2
XAML Essentials By: Mosh Hamedani
Data Binding
<Label Text={Binding
Source={x:Reference slider},
Path=Value,
StringFormat=Value is {0:F2}
} />
When BindingContext applied to a container element, itll be inherited by all its children.
This is useful if we have multiple elements in a StackLayout (or a ContentPage) that
reference the same object as their binding source.
XAML Compilation
To compile our XAML files, we add this in Properties/AssemblyInfo.cs:
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
3
XAML Essentials By: Mosh Hamedani
Padding = Device.OnPlatform<Thickness>(
iOS: new Thickness(0, 20, 0, 0)
Android: new Thickness(0),
WinPhone: new Thickness(0));
Device.OnPlatform(
iOS: () => {
// code to run in iOS only
});