如何将平台专属FontFamily设置作为参数添加到Xamarin Label中?
两种方案实现你的平台特定FontFamily设置
方案1:直接内联到Label属性里
这是最直接的做法,不需要额外配置,直接把OnPlatform嵌套进Label的FontFamily属性节点中即可:
<?xml version="1.0" encoding="utf-8"?> <Label xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Japanese;assembly=Japanese" x:Class="Japanese.Templates.MessageLabel" FontSize="{DynamicResource MessageTextFontSize}" TextColor="{DynamicResource FooterTextColor}"> <!-- 直接在这里添加FontFamily的平台适配 --> <Label.FontFamily> <OnPlatform x:TypeArguments="x:String"> <On Platform="iOS" Value="FontAwesome5ProLight" /> <On Platform="Android" Value="Font Awesome 5 Pro-Light-300.otf#FontAwesome5ProLight" /> </OnPlatform> </Label.FontFamily> </Label>
方案2:提取为可复用的动态资源(作为"参数"复用)
如果你的项目里多个控件都需要用这个字体,推荐把平台适配的字体设置提取成全局/页面级的动态资源,这样就像一个可复用的参数,哪里需要哪里引用:
首先在App.xaml或者当前页面的ResourceDictionary中定义这个资源:
<ResourceDictionary> <!-- 定义可复用的字体资源 --> <OnPlatform x:Key="AwesomeLightFontFamily" x:TypeArguments="x:String"> <On Platform="iOS" Value="FontAwesome5ProLight" /> <On Platform="Android" Value="Font Awesome 5 Pro-Light-300.otf#FontAwesome5ProLight" /> </OnPlatform> <!-- 保留你原有的其他动态资源 --> <x:Double x:Key="MessageTextFontSize">14</x:Double> <Color x:Key="FooterTextColor">#666666</Color> </ResourceDictionary>
然后在你的Label中直接引用这个资源即可:
<?xml version="1.0" encoding="utf-8"?> <Label xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Japanese;assembly=Japanese" x:Class="Japanese.Templates.MessageLabel" FontSize="{DynamicResource MessageTextFontSize}" TextColor="{DynamicResource FooterTextColor}" FontFamily="{DynamicResource AwesomeLightFontFamily}" />
小提示
别忘了做这些前置工作,否则字体可能不生效:
- Android端:把字体文件
Font Awesome 5 Pro-Light-300.otf放到Assets文件夹,并且设置它的Build Action为AndroidAsset - iOS端:把字体文件添加到项目中,然后在
Info.plist的Fonts provided by application列表里添加该字体的文件名
内容的提问来源于stack exchange,提问作者Samantha J T Star
相关产品推荐
相关产品推荐

