C#, .Net and Azure

Font Icons via embedded resources in Xamarin Forms

2020/11/14

In a previous post I had shown how to use Font icons in Xamarin Forms. There was still a small bug in the UWP version that has now been fixed in the latest Xamarin 4.8 release.

Unfortunately alongside the fix the workaround I used started to break. This is not a big deal since now the proper way can be used.

Instead of declaring the full FontFamily everwhere like I did:

<FontImageSource.FontFamily>
    <OnPlatform x:TypeArguments="x:String">
        <On Platform="Android" Value="FontAwesome-regular.otf#Font Awesome 5 Free Regular" />
        <On Platform="UWP" Value="Assets/FontAwesome-regular.otf#Font Awesome 5 Free" />
    </OnPlatform>
</FontImageSource.FontFamily>

one can now simply use:

FontFamily="FontAwesomeRegular"

which only needs to be declared once in the assembly where the font is embedded:

[assembly: ExportFont("FontAwesome-regular.otf", Alias = "FontAwesomeRegular")]

The font can be placed in any directory (no need to specify the folder in the ExportFont attribute) and as long as it’s marked as EmbeddedResource it will work.

One last important point: The assembly containing the font needs to be provided on the Xamarin.Forms.Init() call on the UWP platform, otherwise it is stripped out in release mode.

I have updated my sample on github with the changes as well.