Search code examples
c#wpffonts

How to include external font in WPF application without installing it


How to include external font in WPF application without installing it

I tried this code

  System.Drawing.Text.PrivateFontCollection privateFonts = new    System.Drawing.Text.PrivateFontCollection();
  privateFonts.AddFontFile("C:\\Documents and Settings\\somefont.ttf");
  System.Drawing.Font font = new Font(privateFonts.Families[0], 12);
  this.label1.Font = font;

It working correctly in Windows Form Application but not in WPF.


Solution

  • I use such XAML code:

    <Style x:Key="Hatten">
            <Setter Property="TextElement.FontFamily" Value="Resources/#HATTEN" />
    </Style>
    

    #HATTEN - reference to hatten.tft in Resources.

    Using the Style:

     <TextBlock x:Name="lblTitle" Style="{DynamicResource Hatten}" FontSize="72"></TextBlock>