首页 > 解决方案 > 使用 c# 更改 FontAwesome 文本和 fontfamily - xamarin.forms

问题描述

我在我的解决方案(android 和 ios)中添加了 FontAwesome 字体,我可以毫无问题地从 xaml 使用它。

我的xml代码

   <Label x:Name="Star1" Text="&#xf005;" FontSize="22" FontFamily="{StaticResource FontAwesomeRegular}"/>

应用程序.xaml

        <OnPlatform x:TypeArguments="x:String" 
                    x:Key="FontAwesomeSolid"> 
          <On Platform="Android" 
              Value="FontAwesome5Solid.otf#Regular" /> 
          <On Platform="iOS" 
              Value="FontAwesome5Free-Solid" />  
        </OnPlatform> 

        <OnPlatform x:TypeArguments="x:String" 
                    x:Key="FontAwesomeRegular">
          <On Platform="Android" 
              Value="FontAwesome5Regular.otf#Regular" /> 
          <On Platform="iOS" 
              Value="FontAwesome5Free-Regular" />
        </OnPlatform>

我想在点击时更改某些标签中的 fontfamily 和 Text 值。我尝试以下代码但不工作。

        TapGestureRecognizer starEvent = new TapGestureRecognizer();
        starEvent.Tapped += (sender, e) => {
            Star1.FontFamily = Application.Current.Resources["FontAwesomeSolid"].ToString();
            Star1.Text = "\uf005";
        };

        Star1.GestureRecognizers.Add(starEvent);

Application.Current.Resources["FontAwesomeSolid"].ToString() 返回我

“Xamarin.Forms.OnPlatform`1[System.String]”

标签: c#xamarinxamarin.forms

解决方案


问题是使用OnPlatform. 我不确定为什么它不会像这样工作,我想这与它在内部的铸造方式有关。

试试这个,它应该工作:

Star1.FontFamily = (Xamarin.Forms.OnPlatform<string>)Application.Current.Resources["FontAwesomeSolid"];

推荐阅读