Search code examples
c#xamarinxamarin.formscoding-style

Xamarin Form setter FontFamily reference custom font in same file theme


I am trying to reference a font in a style from my default theme. But I find myself with this error without finding a solution for the moment ...

DefaultTheme.xaml

<Style x:Key="EntryStyle" TargetType="Entry">
    <Setter Property="BorderColor" Value="{StaticResource Gray-300}"/>
    <Setter Property="TextColor" Value="{StaticResource Gray-900}"/>
    <Setter Property="PlaceholderColor" Value="{StaticResource Gray-400}"/>
    <Setter Property="FontFamily" Value="{StaticResource Montserrat-Regular}"/>
    <Setter Property="BackgroundColor" Value="{StaticResource Gray-White}"/>
</Style>

<OnPlatform x:Key="Montserrat-Regular" x:TypeArguments="x:String">
    <OnPlatform.Platforms>
        <On Platform="Android" Value="Montserrat-Regular.ttf#Montserrat-Regular" />
        <On Platform="iOS" Value="Montserrat-Regular" />
        <On Platform="UWP" Value="Assets/Montserrat-Regular.ttf#Montserrat-Regular" />
    </OnPlatform.Platforms>
</OnPlatform>

This is the error I get:

Xamarin.Forms.Xaml.XamlParseException : Position 43:39 StaticResource not found for key Montserrat-Regular

Do you have an idea how to solve this?


Solution

  • It loads the resources in the first in first out order.

    Since you have defined the font resource later, at the time of setting EntryStyle properties its not found.

    Move the Montserrat-Regular above EntryStyle you should be good to go.

    
    <!-- 1st -->
    <OnPlatform x:Key="Montserrat-Regular" x:TypeArguments="x:String">
        <OnPlatform.Platforms>
            <On Platform="Android" Value="Montserrat-Regular.ttf#Montserrat-Regular" />
            <On Platform="iOS" Value="Montserrat-Regular" />
            <On Platform="UWP" Value="Assets/Montserrat-Regular.ttf#Montserrat-Regular" />
        </OnPlatform.Platforms>
    </OnPlatform>
    <!-- 2nd -->
    <Style x:Key="EntryStyle" TargetType="Entry">
        <Setter Property="BorderColor" Value="{StaticResource Gray-300}"/>
        <Setter Property="TextColor" Value="{StaticResource Gray-900}"/>
        <Setter Property="PlaceholderColor" Value="{StaticResource Gray-400}"/>
        <Setter Property="FontFamily" Value="{StaticResource Montserrat-Regular}"/>
        <Setter Property="BackgroundColor" Value="{StaticResource Gray-White}"/>
    </Style>