0

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?

5
  • Same as xaml you can access font family in c# and specify like this: FontFamily="Roboto-Regular.ttf#Roboto-Regular" , as per your fonts. Commented Aug 6, 2019 at 11:09
  • please refer this: learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/… Commented Aug 6, 2019 at 11:10
  • You should be able to access the ResourceDictionary in code behind: Application.Current.Resources["MyResourceName"]. Remember to cast this to the correct type. If you do it this way you won't have to change the font in multiple places if that's ever needed. Also I advise you to define general styles and use those in your controls (that way you can customize a lot more automatically) Commented Aug 6, 2019 at 14:11
  • @Knoop thanks for your answer. I know that it's possible to get the Resouces like that, but my problem is the cast. Whats the type of the "fontFamily"? Commented Aug 6, 2019 at 16:44
  • Ah not sure tbh, and can't check atm since I'm on a phone. However if you define a Style for Label in your ResourceDictionary that sets the FontFamily you can just cast and use that Style in code-behind Commented Aug 7, 2019 at 6:11

2 Answers 2

1

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";
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.