Styles in Xamarin Forms

Like WPF and UWP, Xamarin Forms supports the ability to “style” your application controls.

We can explicitly apply styles by creating a style with a key and explicitly assigning that style to a control. Alternatively we can implicitly apply styles be declaring the type (only) that the style applies to.

Let’s just do something very simple and make our ContentPage a rather bright Lime colour.

Explicit Style

After creating a mobile application within Visual Studio (which will default to using a ContentPage) simply add the following to the App.xaml, within the Application.Resources element.

<ResourceDictionary>
   <Style x:Key="ContentStyle" TargetType="ContentPage" >
      <Setter Property="BackgroundColor" Value="Lime" />
   </Style>
</ResourceDictionary>

In this example, we’ve declared the x:Key as ContentStyle. This is an explicit style in that, to use it, we need to set the Style property on the ContentPage that we want to apply this style to.

Open the MainPage.xaml (or any other ContentPage xaml files you have) and add the following as an attribute to the ContentPage

Style="{StaticResource ContentStyle}"

If you run the application you’ll be presented with a ContentPage with a bright Lime background colour.

If you’ve come from using WPF or UWP you’ll know you can also declare styles to the resource of your page’s so they’re scoped solely to that page. The App.xaml is globally scoped.

Implicit Style

Now, if all our ContentPage objects were to use this style, we might prefer to not have to assign the style each time. Instead we can change our App.xaml Style to look like this

<Style TargetType="ContentPage" ApplyToDerivedTypes="True">
   <Setter Property="BackgroundColor" Value="Lime" />
</Style>

Notice, we’ve removed the x:Key and added the ApplyToDerivedTypes. Now remove the Style attribute from your, previously created, ContentPage and run the application again and you’ll see the Style is automatically applied to all ContentPage objects.

Note: You can use TargetType=”{x:Type ContentPage}”, this more verbose way of declaring the TargetType is not required.