把很棒的字体图标放在c#代码后面

Dav*_*vid 5 xamarin xamarin.forms

目前,我可以使用 XAML 代码中的选项卡测量页面上令人印象深刻的字体图标,如下所示:

<ContentPage.IconImageSource>
    <FontImageSource  FontFamily="{StaticResource Solid }" Glyph="&#xf108;" ></FontImageSource>
</ContentPage.IconImageSource>
Run Code Online (Sandbox Code Playgroud)

这样我就可以在我的应用程序中放置图标,但我想从代码隐藏中进行,因为必须从某些操作中创建该选项卡式页面,并且我以以下方式进行了操作:

 contenido.IconImageSource  = new ContentPage().IconImageSource {
    new FontImageSource().FontFamily = "\uf108";
};
Run Code Online (Sandbox Code Playgroud)

但是在第一个“{”中,我收到错误消息“我希望有一个;”

更新

代码 App.xaml

<Application.Resources>
    <ResourceDictionary>
        <!--Global Styles-->
        <Color x:Key="NavigationPrimary">#2196F3</Color>
        <Style TargetType="NavigationPage">
            <Setter Property="BarBackgroundColor" Value="{StaticResource NavigationPrimary}" />
            <Setter Property="BarTextColor" Value="White" />
        </Style>

        <OnPlatform x:TypeArguments="x:String" 
            x:Key="Brands">
            <On Platform="Android" 
      Value="BrandsRegular.otf#Regular" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String" 
            x:Key="Regular">
            <On Platform="Android" 
      Value="FreeRegular.otf#Regular" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String" 
            x:Key="Solid">
            <On Platform="Android" 
      Value="FreeSolid.otf#Regular" />
        </OnPlatform>


    </ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

pin*_*dax 5

您不需要创建新的 ContentPage,只需创建一个FontImageSource对象并相应地设置值,然后将此对象传递给IconImageSource您的contenido页面。

此外,您还需要从 App Resources Dictionary 中获取 StaticResource。

这样的事情应该工作:

var solidFontFamily = Application.Current.Resources["Solid"] as OnPlatform<string>;
contenido.IconImageSource = new FontImageSource() { FontFamily = solidFontFamily, Glyph= "\uf108" };
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。-

  • 代码是正确的,但你的转换是错误的,你必须转换 OnPlatform&lt;string&gt; 而不是 string,就像这样 var SolidFontFamily = Application.Current.Resources["Solid"] as OnPlatform&lt;string&gt;; (3认同)