Max Dunger
Max Dunger

Reputation: 3

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?

Upvotes: 0

Views: 1715

Answers (2)

MichelPeseur
MichelPeseur

Reputation: 187

You can access your font from c# using the following cast:

var yourFont = (OnPlatform<string>)Application.Current.Resources["FONT"];

Upvotes: 0

Lucas Zhang
Lucas Zhang

Reputation: 18861

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";
}

Upvotes: 1

Related Questions