It is in general considered good practices to avoid magic strings and numbers in your code. Instead, it is recommended to define some sort of constant values in your app that you can reference throughout your code. That being said, we have all seen XAML code that kind of look like this:

<ContentPage>
    <StackLayout> 
        <Label TextColor="red" FontSize="17" ... />
        <Button BackgroundColor="red" FontSize="17" ... /> 
        <Button BackgroundColor="red" FontSize="17" ... />
        ...
    </StackLayout>
</ContentPage>     

See this red and 17 defined everywhere throughout the markup? Why do we tend to treat XAML markup and code differently? And why should we care?
Magic numbers and strings in the markup is going to make the app very hard to maintain in the long run. Consider those simple scenarios:

Wouldn’t it be awesome if we could reference some constant values directly in the markup instead? {x:Static} to the rescue!

{x:Static} can access any public static field, property or constant defined by a class or a struct. How can we use it in our markup?

First let’s define a static class with the properties we’d like to share:

namespace MyApp
{
    public static class AppConstants
    {
        public static readonly Color BackColor = Color.Red;
        public static readonly double FontSize = 17;
        ...
    }
}   

Then we can use the {x:Static} markup extension to reference those colors from our XAML page.

<ContentPage ...xmlns:local="clr-namespace:MyApp;assembly=MyApp" ...>
    <StackLayout> 
        <Label TextColor="{x:Static local:AppConstants.BackColor}" FontSize="{x:Static local:AppConstants.FontSize}" ... />
        <Button BackgroundColor="{x:Static local:AppConstants.BackColor}" FontSize="{x:Static local:AppConstants.FontSize}"... /> 
        <Button BackgroundColor="{x:Static local:AppConstants.BackColor}" FontSize="{x:Static local:AppConstants.FontSize}" ... />
        ...
    </StackLayout>
</ContentPage>    

That’s it! No more magic string and number! And as a nice free bonus: you can now easily find with the Resharper function Find Usage or (ALT+F7) where those constants are being used. Sweet! In a future post, we will see how the usage of Resources and Styles will help us reduce the code redundancy even more. Stay tuned!