user4071320
user4071320

Reputation:

Change font of my application in Xamarin Forms (all label/listview...)

I would like to change my fontfamilly with custom font of my application.

In the Xamarin documentation, i can see how i can change the fontfamilly just for one label, but not for my total application !

I work with Xamarin Forms for Android and IOS !

I need to change the font for my : -Listviews -Buttons -Label

Thank you

Upvotes: 1

Views: 6067

Answers (2)

Florian
Florian

Reputation: 485

This way you can use XAML code like you intended to:

<Label FontFamily="Arial" Text="Hi there" />

Android You can overwrite the default Renderer for all views you need it for. Here is an example for Label. You can do the same for listview and button.

[assembly: ExportRenderer (typeof (Label), typeof (MyLabelRenderer))]
namespace MyApp.Droid
{
    public class MyLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            if ( !String.IsNullOrEmpty(Element.FontFamily) )
                Control.Typeface = Typeface.CreateFromAsset(Forms.Context.Assets, "Fonts/" + Element.FontFamily + ".otf");
        }
    }
}

Of course you need to map that to the location where you embedded the custom font. In my case Assets/Fonts/Arial.otf (Build Action: AndroidAsset).

In iOS you need to add it to the Resources folder: Resources/Arial.otf (Build Action: BundleResource) and it should work with the XAML code above.

Upvotes: 1

Jason
Jason

Reputation: 89082

You can use a Global Style to apply a change to all elements in your App. To change the font of all Label elements, you could do this:

<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Styles.App">
    <Application.Resources>
        <ResourceDictionary>
            <Style TargetType="Label">
                <Setter Property="FontFamily" Value="sans-serif" />
                <Setter Property="FontSize" Value="12" />
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Upvotes: 5

Related Questions