In WPF, how do I reference a font in a resource library in code behind?

c#, fonts, pack-uri, wpf

Solution

I have it working in my application (loading fonts from another assembly in code-behind). For a font URI like this:

pack://application:,,,/MyAssembly.Name;component/Resources/Fonts/#Swis721 Md BT

The way I got it to work (after painful trial and error, if I remember correctly) is:

new FontFamily(
    new Uri("pack://application:,,,/MyAssembly.Name;component/Resources/Fonts/"),
    "./#Swis721 Md BT"
)

Hope that helps.

Problem

I have an application that uses a separate library assembly for resources (but not a resource-only assembly with no code), and I would like to include a custom font in the library. I am able to get the font, which is an `Open Type Font`, to load if I add its .otf file as a resource to the project for the executing assembly (rather than to the resource library project), with properties set as Build Action = 'Resource' and Copy to Output = 'Do Not Copy', by using the following code: ``` FontFamily font = new FontFamily(new Uri("pack://application:,,,/"), "./Resources/#CustomFont")); // Resources is a subfolder ``` When I try to add the font to the resource library project, however, the font does not load. I tried using the following code to load it (also of note: I do not have much experience with pack URIs): ``` FontFamily font = new FontFamily(new Uri("pack://application:,,,/MyLibrary"), "./Resources/#CustomFont")); // there is a Resources subfolder in my library as well // not sure about whether I need the . ``` The library does work for other resources, such as images. I've also tried a bunch of other permutations for the URI with no success (it also does not throw exceptions, just displays with the default font, not sure if this is a separate issue). I've been working from Packaging Fonts with Applications on MSDN, which has an example of creating a font resource library, but no examples using code behind (I am forced to use code behind for this). Any ideas about what I need to do? Am I off track?

Original source

Related problems