FontFamily XAML Entry

Inject the Font Family XAML entry for a font asset the Resource Dictionary of a Xamarin.Forms App


Xamarin.Forms projects allows declaring font references as Resources in Resource Dictionaries, which can be set on Font property of most of the Forms components that has some form of text (such as Labels and Buttons).

Fonts references in Xamarin.Forms are declared as plain strings, but each platform expects the string in a different format. For this reason we use the OnPlatform element to reference the font in the expected way for each platform. The code snippet below shows an example of this is done:

    <OnPlatform x:TypeArguments="x:String" x:Key="OpenSans">
        <On Platform="iOS" Value="OpenSans"/>
        <On Platform="Android" Value="OpenSans-Regular.ttf#Regular"/>
    <!-- Other dictionary resources -->

The Font Importer can add this to the App.xaml file, which makes the font reference available to any XAML file in the project, but it can also be added to the Resources Dictionary of a specific file.

To customise the font of a component based on this entry, you should use the StaticResource markup extension of XAML. As an example, suppose a Page where we have a label that we want to apply the custom font:

    <StackLayout VerticalOptions="Center">
            FontFamily="{StaticResource OpenSans}"
            Text="Welcome to MFractor Docs!" />

Screenshot of the page with a custom font applied in iOS Screenshot of the page with a custom font applied in Android