首页 > 解决方案 > 没有特定 TargetType 的应用程序的多个自定义字体

问题描述

我正在尝试将两种自定义字体导入我的应用程序。现在,我已经分别在.Droid/Assets.iOS/Resources目录中添加了字体,iOS 将它加载到我的 Info.plist 中。

在我的 App.xaml 中,我执行以下操作以在我的 PCL 中加载字体:

<Application.Resources>
    <ResourceDictionary>
        <Style x:Name="BoldFont" TargetType="Label">
            <Setter Property="Label.FontFamily">
                <Setter.Value>
                    <OnPlatform x:TypeArguments="x:String">
                        <OnPlatform.Android>PT_Sans-Narrow-Web-Regular.ttf#PT Sans Narrow</OnPlatform.Android>
                        <OnPlatform.iOS>PT Sans Narrow</OnPlatform.iOS>
                    </OnPlatform>
                </Setter.Value>
            </Setter>
        </Style>
    </ResourceDictionary>
</Application.Resources>

但是,我希望能够在我的标签中使用多种字体,这就是我将以下代码添加到我的原因<ResourceDictionary>

<Style x:Name="RegularFont" TargetType="Label">
    <Setter Property="Label.FontFamily">
        <Setter.Value>
            <OnPlatform x:TypeArguments="x:String">
                <OnPlatform.Android>RobotoCondensed-Regular.ttf#Roboto Condensed</OnPlatform.Android>
                <OnPlatform.iOS>Roboto Condensed</OnPlatform.iOS>
            </OnPlatform>
        </Setter.Value>
    </Setter>
</Style>

不幸的是,我收到了错误:

ResourceDictionary 中已存在具有键“Xamarin.Forms.Label”的资源

此外,我真的必须使我的 TargetType 特定于标签,如果说,我想全局使用字体,不管它是 aLabel还是 an Entry

标签: xamarin.forms

解决方案


首先,对于 Style,使用 x:Key 而不是 x:Name。这将避免您看到的错误消息。

<Style x:Key="RegularFont" TargetType="Label">
    <Setter Property="Label.FontFamily">
        <Setter.Value>
            <OnPlatform x:TypeArguments="x:String">
                <OnPlatform.Android>RobotoCondensed-Regular.ttf#Roboto Condensed</OnPlatform.Android>
                <OnPlatform.iOS>Roboto Condensed</OnPlatform.iOS>
            </OnPlatform>
        </Setter.Value>
    </Setter>
</Style>

有时您可以在类型之间共享样式定义。最好的方法是使用 TargetType,它是一个通用基类,它定义了您要设置的属性。不幸的是,Label 和 Entry 之间没有这样的通用基类。它们各自独立定义 FontFamily。


推荐阅读