Xamarin styles: Tips on managing XAML files

2019-07-26 10_11_57-artboard_2_1x.png (400×300).pngXamarin offers a wide range of style options to help you make your app consistent, and easy to change. Here are a few tips on how to manage a lot of style settings.

Let’s first create a xaml file with some simple styles. Create a new file in your main project called ThemeFonts.xaml. In this example, I create references for Font Awesome Pro fonts.

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
                    x:Class="App.Themes.ThemeFonts">
 
    <OnPlatform x:Key="FontAwesomeLightFontFamily" x:TypeArguments="x:String"
                Android="fa-light-300.ttf#Font Awesome 5 Pro Light"
                iOS="FontAwesome5Pro-Light"/>
 
    <OnPlatform x:Key="FontAwesomeSolidFontFamily" x:TypeArguments="x:String"
                Android="fa-solid-900.ttf#Font Awesome 5 Pro Solid"
                iOS="FontAwesome5Pro-Solid" />
 
    <Style x:Key="FontAwesomeFontIcon" TargetType="Label">
        <Setter Property="FontFamily" Value="{DynamicResource FontAwesomeLightFontFamily}" />
    </Style>
 
    <Style x:Key="FontAwesomeFontIconSolid" TargetType="Label">
        <Setter Property="FontFamily" Value="{DynamicResource FontAwesomeSolidFontFamily}" />
    </Style>
</ResourceDictionary>

Make sure the Properties are set like this:

2019-07-26 10_02_02-BpApp - Microsoft Visual Studio.png

Now just reference this new file in your App.xaml.

Now your App.xaml is nice a clean. You can add more style xaml pages, each with an area of responsibility, to your app.

<?xml version="1.0" encoding="utf-8"?>
 
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:themes="clr-namespace:App.Themes;assembly=App"
             mc:Ignorable="d"
             x:Class="App.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <themes:ThemeFonts/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s