Using Font Awesome in WPF

Font Awesome is a css library that includes many scalable vector icons. This library is widely used in many web apps.

In this post I will show you how to use Font Awesome in a WPF App.

Creating the Solution

First of all, we create a new WPF app by selecting Project from the File -> New Menu.

Under Installed -> Templates ->Visual C#, we select WPF Application.

For this example, we enter FontAwesomeWPFDemo for the solution Name and we click OK.

01-createWpfProject

Adding Font Awesome

We’ll download Font Awesome from this Link.

Next, we’ll create a new Folder in our WPF Demo Project called fonts.

We’ll add font-awesome.css and fontawesome-webfont.ttf to the fonts folder.

02-createFontsFolder

We’ll make sure to change the Build Action for fontawesome-webfont.ttf to Resource.

05-resourceProperties

Parsing the CSS File

In oder to use the Font Awesome Icons in our WPF Demo App. We’ll need to parse the recentely added font-awesome.css File. We’ll use this Gist on GitHub.

We’ll add a T4-Template named CssParser.tt. We’ll implement the template as follows:

The methods to note are GetFontAwesomeIcons and AddStyleSheet. All they really do is to parse the given css file path and return a dictionary with valid C# variable names and fonts unicode strings;

Next, we’ll add another T4-Template File named FA.tt. We’ll implement the template as follows:

This Template use the CssParser.tt that we included to generate a static Fa.cs class that contains all icons unicode strings.

Using Font Awesome in WPF App

We’ll implement the MainWindow.xaml as follows:

In Line 10: FontAwesomeStyle style will be applied to all instances of the TextBlock element having the the attribute Style="{StaticResource FontAwesomeStyle}":

I hope that was informative for you!

Feel free to drop some comments if you have questions.
The full example code can be found at: Github

Leave a Reply

Next ArticleCreating and Publishing Your Own NuGet Package