FontAwesome / Xamarin - Setting Glyph not working from code behind

假如想象 提交于 2020-08-19 11:03:26

问题


I missing something here when using FontAwesome on Xamarin... the buttons work fine when setting from xaml file but when I try to set from code behind it doesn't show the icon, here is the scenario:

button working fine:

<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>

Last time I had to set Glyph from code, I had to do a bad 'workaround' with converter in order to show it, and it worked (icon is showing) in the end:

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}}

NOW I want to create a custom button and set the Glyph but the icon is not appearing (tested with both OTF and TTF files):

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()},
                }
            };
        }

Any sugestions? Thanks!


回答1:


Here is the sample code, please change accordingly. I am using the FontFile name directly:

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

        this.IconImageSource = fontImageSource;


来源:https://stackoverflow.com/questions/61258115/fontawesome-xamarin-setting-glyph-not-working-from-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!