Javid
Javid

Reputation: 2945

How to load external font file in WPF on runtime

This question has already been asked and I've tried every given solution but yet it's not working for me. I have a TTF file somewhere on my hard disk and I try to load and use it when a button is clicked without the use of XAML. It's totally dynamic so I don't want to get involved with resources.

Here's my code:

var path = @"D:\Fonts\Ashley.ttf";
btn.FontFamily = new FontFamily(new Uri(path), "Ashley");

But it doesn't work. Can you give me a working solution?

Upvotes: 2

Views: 1637

Answers (1)

Mikael Koskinen
Mikael Koskinen

Reputation: 12916

Unfortunately it's not possible to directly reference the font file path. You need two things: The directory where the font file exists and the font name.

So in your case you can set the font family using the following code:

btn.FontFamily = new FontFamily("file:///d:/Fonts/#Ashley");

For reference see chapter Specifying Fonts in Alternate Directories in the MSDN document "FontFamily Class".

Upvotes: 4

Related Questions