0

我正在尝试使用 app.xaml 中的样式为整个 xamarin 表单应用程序设置自定义字体。但我得到了同样的未处理异常。

<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>

在我的内容页面中使用样式如下

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

有什么解决办法吗?

4

1 回答 1

0

如果要使用字体文件为所有标签设置字体,则需要创建自定义渲染器。在那里,像这样覆盖 OnElementChanged:

 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);
        }
    }

但是,如果您希望能够为每个标签设置自定义字体,您需要创建(在 pcl 中)从 Label 继承的自定义标签类并向其添加字体属性(准确地说 - 您将使用的属性传递字体文件的路径)。

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); }
    }

然后在您的渲染器中,您可以像这样读取此属性:

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

请注意,Android 中的路径使用“/”作为分隔符,而不是“。” 就像在表格中一样。

于 2016-10-09T11:48:33.117 回答