简体   繁体   中英

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

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM