xamarin.forms - 没有特定 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
?
解决方案
首先,对于 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。
推荐阅读
- python - 我怎样才能整齐地格式化我的蜘蛛 CSV 导出?
- c# - 刷新后在标签中显示文本
- python-3.x - PyTesseract image_to_data 函数无法识别我的图像
- docker - 无法运行本地 docker 映像
- java - 在 arraylist 对象中使用 split() 方法代码不完整
- c++ - boost io服务对象
- batch-file - 如何使它不显示执行代码的 bat 文件的 cmd 窗口的第一行?
- c# - Assert.Throws 方法没有捕捉到预期的异常
- c++ - 类中的运算符(“C++ 需要所有声明的类型说明符”)
- ssl - .NET Core 处理 HTTPS 证书时出现未知错误