using FontIcon Glyph from code (C#)

Sven Borden picture Sven Borden · Feb 28, 2016 · Viewed 8.9k times · Source

I try to add some of the base provided icon from FontIcon class for universal windows 10 apps (those that we can see mostly in appbar). when running this piece of code, it run without any problem, but in fact, it shows some border square, such as non recognized emoticon character.

Button infoButton = new Button();
infoButton.Content = new FontIcon
{
    FontFamily = new FontFamily("Segoe MDL2 Assets"),
    Glyph = "",
    Foreground = new SolidColorBrush(Colors.WhiteSmoke)
};

Answer

Grace Feng picture Grace Feng · Feb 29, 2016

This is the problem how XAML and C# deal with the Unicode Characters. When you use this in XAML code, it is something like Glyph = "", but when you use this in the C# code, it should be like this: Glyph = "\uE946".

There is no specific document for this details, but some cases on MSDN & SO forum have the same implementation: AppBarButton.Icon doesn't change on runtime.

In C# code behind, we need to use the escape character.