Search code examples
c#xamlxamarin.formsfonts

Xamarin.Forms: How to use custom Fonts in C# Code


I want to use some custom Fonts (.ttf) in my Xamarin.Forms Application. I added the two Fonts in both Projects(Android/iOS):

Now in the XAML-Page, I added the Fonts to the ResourceDictionary. It's also possible to use the Fonts, but just in the XAML-File:

<Label Text="Test" FontFamily="{StaticResource FONT}" FontSize="Medium"/>

But how can I use this font in the C# Code?


Solution

  • The Device.RuntimePlatform property can be used to set different font names on each platform.

    if (Device.RuntimePlatform == Device.iOS)
    {
        label.FontFamily = "xxx.ttf";
    }
    
    else if (Device.RuntimePlatform == Device.Android)
    {
        label.FontFamily = "xxx.ttf#xxx";
    }
    
    else
    {
        label.FontFamily = "Assets/Fonts/xxx.ttf#xxx";
    }