user3165999
user3165999

Reputation: 159

How to set custom font for xamarinf forms application

Iam trying to set custom font for entire xamarin forms app using style in app.xaml. But Im getting unhandled exception for the same.

<OnPlatform x:Key="AppFontFamily" x:TypeArguments="x:String"
      Android="customfont.otf#CustomFont-Regular">
</OnPlatform>

<Style x:Key="labelFont" TargetType="Label">
        <SetterProperty Property="FontFamily" Value="{StaticResource AppFontFamily}"></SetterProperty>
      </Style>

Using style in my content page as follows

<Label Style="{StaticResource labelFont}"></Label>

Any solution for this?

Upvotes: 0

Views: 501

Answers (1)

maddhew
maddhew

Reputation: 54

If you want to set a font for all labels using a font file you need to create a custom renderer. There, override OnElementChanged like this:

 protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        try
        {
            Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, path);
            Control.Typeface = font;
        }
        catch(Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Unable to make typeface:" + ex);
        }
    }

However, if you want to be able to set a custom font for every single label you need to create (in pcl) a custom label class inheriting from Label and add to it a font property (to be precise - property which you'll use to pass font file's path).

public static readonly BindableProperty CustomFontProperty =
        BindableProperty.Create(
            "CustomFont",
            typeof(string),
            typeof(CustomLabel),
            default(string));

    public string CustomFont
    {
        get { return (string)GetValue(CustomFontProperty); }
        set { SetValue(CustomFontProperty, value); }
    }

Then in your renderer you can read this property like this:

var label = Element as CustomLabel;
string path = label.CustomFont;

Be aware that path in Android uses '/' as separators, not '.' as in Forms.

Upvotes: 0

Related Questions