Styling

If you come from a web background you certainly want to know how to create a stylesheet of sorts to hold all of your UI styling information. As always, this is the XAML way.

Creating your App.xaml.cs

You will notice that by default you have an App.cs in your project. What you need to do is delete that, then create create a Xamarin Page call App. You will get App.xaml.cs and App.xaml.

Copy what you had in your App.cs into the App.xaml.cs. Then also go into the XAML and change the ContentPage with Application. You can see an example further down the post.

Initialize Component

Little trick here, in the constructor of the page add in InitializeComponent();

public App()
{

    InitializeComponent();

    MainPage = "whatever you had before";

}

Adding Style Resource

Put this in the App.xaml.cs

<?xml version="1.0" encoding="utf-8" ?>
<Application
 xmlns="http://xamarin.com/schemas/2014/forms"
 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
 x:Class="Mobile.App">
 <Application.Resources>
     <ResourceDictionary>
         <Style x:Key="LabelStyle" TargetType="Label">
         <Setter Property="VerticalOptions" Value="Center"/>
         <Setter Property="FontSize">
             <Setter.Value>
                 <OnPlatform x:TypeArguments="x:Double" iOS="18" WinPhone="24" Android="18" />
             </Setter.Value>
          </Setter>
          <Setter Property="FontFamily" Value="Helvetica"/>
          <Setter Property="TextColor" Value="White"/>
          </Style> 
     </ResourceDictionary>
 </Application.Resources>
</Application>

Using a Style Resource

Use your style as desired.

<Label Text="Some Text" Style="{StaticResource LabelStyle}" />
Microsoft MVP | Xamarin Certified Developer |
Exrin Creator | Xamarin Forms Developer | Melbourne, Australia
Tagged:Tags:

Leave A Comment?