Search code examples
c#.netxamltextblock

XAML TextBlock set special characters programmatically?


I want to use font awesome (http://fortawesome.github.io/Font-Awesome/design.html) in XAML.

I have been able to easily get it to work via direct XAML, by creating a fonts folder and adding the font there, then in XAML:

<TextBlock FontFamily="Fonts/#FontAwesome">&#xf000;</TextBlock>

Displays a martini glass icon.

However, when adding it programmatically it just shows and invalid symbol like so: [], I tried the following:

XAML:

<TextBlock Name="textBlock"></TextBlock>

C#:

textBlock.FontFamily = new FontFamily("Fonts/#FontAwesome");
textBlock.Text = HttpUtility.HtmlDecode("&#xf000;");

and the following which returns the literal string:

textBlock.FontFamily = new FontFamily("Fonts/#FontAwesome");
textBlock.Text = "&#xf000;";

Any ideas?


Solution

  • try the following :

    textBlock.FontFamily= new FontFamily(new Uri("pack://application:,,,/"), @"/Fonts/#FontAwesome"); // you should well reference your font else you will get a square
    textBlock.Text = "\uf000";// \u (unicode escape char) instead of &#x
    

    and if you want to preview your textblock XAML use

    t_out.Text = XamlWriter.Save(textBlock);