Font Awesome is often used in web development. Today describes how to use font Awesome in a WPF application.
If it is a custom icon font, use the same method.
Download icon Font
Download resources on the official website or on GitHub
http://fontawesome.io/#modal-download
Https://github.com/FortAwesome/Font-Awesome
Unzip the downloaded file (I'm downloading the source on GitHub) and we're going to use the content in the CSS and fonts folders
adding fonts to your project
- Create a new WPF app and create a new folder for the fonts;
- Copy the Fontawesome-webfont.ttf in the downloaded Fonts folder to the folder where the font is stored in the project and set its build action to resource (default is);
First add fonts to the resource
<FontFamily x:Key="IconFont">/IconFontSample;component/fonts/fontawesome-webfont.ttf#Fontawesome</FontFamily>
Then add the style
<Style x:Key="IconStyle" > <Setter Property="TextElement.FontFamily" Value="{StaticResource IconFont}" /> <Setter Property="Control.OverridesDefaultStyle" Value="True"></Setter> <Setter Property="Control.UseLayoutRounding" Value="True"></Setter> <Setter Property="Control.SnapsToDevicePixels" Value="True"></Setter> <Setter Property="TextBlock.TextAlignment" Value="Center"></Setter> <Setter Property="TextBlock.VerticalAlignment" Value="Center"></Setter> <Setter Property="TextElement.FontSize" Value="12"></Setter> </Style>
Process Icon Resource Name
Now, we need to add fonts in the form of WPF resources, and we need to put the CSS
Processed into
<system:String x:Key="icon-glass"></system:String>
There are actually more ways to deal with it, such as writing a script or something. I am here to introduce the method of direct use substitution
Open the Font-awesome.css file in vs. (in the downloaded CSS folder)
Delete other CSS styles except for the following format
.fa-glass:before { content: "\f000";}
Use the <system:String x:Key="
replace.
Use the ">
replace:before {
Use the &#x
replacecontent: "\
Use the ;
replace";
Use the </system:String>
replace}
In the resource file, addxmlns:system="clr-namespace:System;assembly=mscorlib"
, delete lines 2000 and 2001
Use
Once you have done this, we can use it in the application.
In the App.xaml file, the introduction of resources
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/IconFontSample;component/fonts/IconFontDictionary.xaml"></ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
In the application, you can use resources in a way that uses the
<TextBlock Style="{DynamicResource IconStyle}" FontSize="26" Text="{DynamicResource fa-recycle}" Foreground="Brown"></TextBlock>
You can set the size and color of icons by setting fontsize and foreground
Using the font awesome icon in a WPF application