首页 > 解决方案 > FontAwesome / Xamarin - 设置字形不能从后面的代码中工作

问题描述

在 Xamarin 上使用 FontAwesome 时,我在这里遗漏了一些东西......从 xaml 文件设置时按钮工作正常,但是当我尝试从其后面的代码设置时,它不显示图标,这是场景:

按钮工作正常:

<Button Grid.Row="0" Grid.Column="4" x:Name="btnIdDav" Padding="10" Margin="3" TextColor="#FFF" BackgroundColor="#565C5A" Clicked="btnIdDav_Clicked" WidthRequest="45">
   <Button.ImageSource>
      <FontImageSource FontFamily="{StaticResource FontAwesomeSolidOTF}" Glyph="&#xf039;" Color="#fff"/>
   </Button.ImageSource>
</Button>

上次我不得不从代码中设置字形时,我不得不用转换器做一个糟糕的“解决方法”才能显示它,它最终起作用了(图标正在显示):

public const string _dollarGlyph = "\uf155";
public const string _percGlyph = "\uf541";
 public class DescGlyphConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
Glyph="{Binding DescImage, Converter={StaticResource Key=desconto}}

现在我想创建一个自定义按钮并设置字形,但图标没有出现(用 OTF 和 TTF 文件测试):

public static FontImageSource GetImgSource()
        {
            FontImageSource source = new FontImageSource();
            source.FontFamily = Application.Current.Resources["FontAwesomeSolidTTF"].ToString();
            source.Glyph = "\uf3e5";
            source.Color = Color.FromHex("#fff");
            return source;
        }

        public static Style BtnBack() {
            return new Style(typeof(Button))
            {
                Setters = {
                    new Setter { Property = Button.ContentLayoutProperty, Value = new ButtonContentLayout(ButtonContentLayout.ImagePosition.Top, 5) },
                    new Setter { Property = Button.TextProperty, Value = "Back" },
                    new Setter { Property = Button.ImageSourceProperty, Value = GetImgSource()},
                }
            };
        }

有什么建议吗?谢谢!

标签: c#androidxamarinfont-awesomeglyph

解决方案


这是示例代码,请相应更改。我直接使用 FontFile 名称:

FontImageSource fontImageSource = new FontImageSource()
        {
            Glyph = "\uf15c",
            Color = Color.Black,
            Size = 18,
            FontFamily = Device.RuntimePlatform == Device.Android ? "FontAwesome.otf#Regular" : null
        };

        this.IconImageSource = fontImageSource;

推荐阅读