How can I set ResourceDictionary FontSize on XAML?

时间:2018-03-22 23:55:52

标签: xamarin xamarin.forms

Apologies if this would be a messy one. I'm pretty new to Xamarin. Currently I'm trying to convert this resource dictionary code to a XAML:

Current.Resources = new ResourceDictionary {
  { FontResources.DefaultButtonFontAttribute, FontAttributes.Bold }, 
  { FontResources.DefaultLabelFontSize, 
 Xamarin.Forms.Device.GetNamedSize(NamedSize.Small, typeof(Label)) }, 
  { StyleResources.DefaultLabelStyle, LABEL_STYLE }    
}

(FontResources and StyleResources is a RESX file that contains the key name) Having

public static Style LABEL_STYLE = new Style(typeof(Label))
        {
            Setters = {
                new Setter { Property = Label.FontSizeProperty, Value = new DynamicResource( FontResources.DefaultLabelFontSize )},
                new Setter { Property = Label.FontAttributesProperty, Value = new DynamicResource( FontResources.DefaultLabelFontAttribute )},
            }
};

The way I'm trying to do this is like this:

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Styles.App">
    <Application.Resources>
        <ResourceDictionary>
            <FontAttributes x:Key="DefaultLabelFontAttribute"></FontAttributes>
            <FontSize x:Key="DefaultLabelFontSize"></FontSize>
            <Style x:Key="DefaultLabelStyle" TargetType="Label">
                <Setter Property="FontAttributes" Value="{DynamicResource DefaultLabelFontAttribute}"></Setter>
                <Setter Property="FontSize" Value="{DynamicResource DefaultLabelFontSize}"></Setter>
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

But it seems that I'm not doing it the right way as there's no FontSize property similar to the FontAttribute. All I can see is FontSizeConverter. Also is there a way to call this code: Xamarin.Forms.Device.GetNamedSize(NamedSize.Small, typeof(Label)) to the Xaml?

1 个答案:

答案 0 :(得分:3)

Also is there a way to call this code: Xamarin.Forms.Device.GetNamedSize(NamedSize.Small, typeof(Label)) to the Xaml?

ResourceDictionary:

<ResourceDictionary>
    <Style x:Key="Labelfont" TargetType="Label">
        <Setter Property="FontSize" Value="Small" />
    </Style>
</ResourceDictionary>

Style Usage:

Label Text="UsingSmallFont" Style="{StaticResource Labelfont}"/>