Search code examples
c#xamarin.formsfontsglyphmaterial-design-icons

Issue with FontImageSource Glyph when using a Binding


Using Xamarin Forms 5 and Visual Studio 2022.

I have added the materialdesignicons-webfont.ttf to a Fonts folder of the PCL project only and marked it as an Embedded Resource.

I have added the following in the AssemblyInfo.cs file:

[assembly: ExportFont("materialdesignicons-webfont.ttf", Alias = "mdi")]

The following XAML works fine:

<Image x:DataType="models:IPageResourceProvider"
        BackgroundColor="Transparent"
        IsVisible="{Binding IconType, Converter={StaticResource IconTypeConverter}, ConverterParameter={x:Static enums:IconType.MaterialDesignIcon}}">
    <Image.Source>
        <FontImageSource Glyph="&#xF0B55;"
                          FontFamily="mdi"
                          Size="32"
                          Color="Black" />
    </Image.Source>
</Image>

But I want to bind the Glyph, however the following just shows a 5 as the Image (the last character of the unicode):

<Image x:DataType="models:IPageResourceProvider"
        BackgroundColor="Transparent"
        IsVisible="{Binding IconType, Converter={StaticResource IconTypeConverter}, ConverterParameter={x:Static enums:IconType.MaterialDesignIcon}}">
    <Image.Source>
        <FontImageSource Glyph="{Binding IconName}"
                          FontFamily="mdi"
                          Size="32"
                          Color="Black" />
    </Image.Source>
</Image>

The interface IPageResourceProvider has the following property:

string IconName {get; }

And the implementation returns:

string IconName => "\uF0B55";

I can't work out what I'm doing wrong with this, any thoughts welcomed.


Solution

  • In C# represent a UTF-32 glyph using 4 bytes.

    Example in C# for glyph U+10FFFD. Please note the upper case U:

    public string IconName => "\U0010FFFD";
    

    See also the note on four-digit and eight-digit Unicode escape codes here.

    Example in XAML for glyph U+10FFFD:

    Glyph="&#x10FFFD;"