WPF: How to Reference Font Resource File

External font file

1. Background code reference font

We call it “Chinese” CharacterSpecialFont.ttf ”The TTF file is placed in the desktop path, and the background reference method is as follows:

1 var ttfFilePath = @"C:\Users\user\Desktop\";
2 HanziTextBlock.FontFamily = new System.Windows.Media.FontFamily(new Uri(ttfFilePath), "./#楷体_GB2312");

The path URI only needs a folder, and the next parameter family is “.”/# specify font type name “.

be careful:

The path URI is not the full path of the TTF file; the folder where the TTF file is located needs to be added with ‘/’ or ‘\ \’; any special character in the parameter family cannot be missing. Otherwise, the characters displayed in the interface will not be displayed in the specified font. The reference font has nothing to do with the name of the font file, only the font type name can be referenced.

#The font type name is indicated after it. You can double-click to open the TTF file

2. WPF XAML resource reference

Call it Chinese CharacterSpecialFont.ttf ”Ttf file, in the wpfapp2 project. The quotation is as follows:

1     <Window.Resources>
2         <FontFamily x:Key="HanziCharacterFontFamily">pack://application:,,,/WpfApp2;component/#楷体_GB2312</FontFamily>
3     </Window.Resources>
4     <Grid>
5         <TextBlock x:Name="HanziTextBlock" Text="a" FontFamily="{StaticResource HanziCharacterFontFamily}"
6                    FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Center"/>
7     </Grid>

Install font files locally

The local installed fonts can be downloaded through Fonts.SystemFontFamilies obtain.

The XAML font goes without saying. You can set the font type in the background by:

1     var systemFontFamilies = Fonts.SystemFontFamilies;
2     var songTiFamily = systemFontFamilies.FirstOrDefault(i=>i.Source=="KaiTi");
3     HanziTextBlock.FontFamily = songTiFamily;

The system font is fontfamily data, and the source name is in English. How to get the corresponding font by Chinese name?

Familynames is a dictionary containing multi language items. Key is the language item and value is the font type name.

 1     var systemFontFamilies = Fonts.SystemFontFamilies;
 2     FontFamily filteredChineseFamily = null;
 3     foreach (FontFamily family in systemFontFamilies)
 4     {
 5         LanguageSpecificStringDictionary familyNames = family.FamilyNames;
 6         if (familyNames.ContainsKey(XmlLanguage.GetLanguage("zh-cn")))
 7         {
 8             if (familyNames.TryGetValue(XmlLanguage.GetLanguage("zh-cn"), out var chineseFontName)&&chineseFontName=="楷体")
 9             {
10                 filteredChineseFamily = family;
11                 break;
12             }
13         }
14     }
15     HanziTextBlock.FontFamily = filteredChineseFamily;

Keywords: TTF font referenced by background code, TTF font referenced by WPF front end


Read More: