DSK
DSK

Reputation: 63

How to set FontFamily in code

I'm creating a WPF application where I need to use custom fonts. A created a font resource library as described here http://msdn.microsoft.com/en-us/library/ms753303.aspx. An example shows how to set a font family in XAML:

<Run FontFamily="/FontLibrary;Component/#Kootenay" FontSize="36">
  ABCDEFGHIJKLMNOPQRSTUVWXYZ
</Run>

How do I set a font family in the code?

Upvotes: 6

Views: 9836

Answers (2)

nPcomp
nPcomp

Reputation: 9833

First, give your element a name.

<Run x:Name="someNameHere">ABCDEFGHIJKLMNOPQRSTUVWXYZ</Run>

and now in the code behind you can do set it like in the following examples:

someNameHere.FontFamily = new FontFamily("Monospace");

or

someNameHere.FontFamily = new FontFamily("Comic Sans MS");

or

someNameHere.FontFamily = new FontFamily("Times New Roman");

Upvotes: 1

Ed Bayiates
Ed Bayiates

Reputation: 11210

Assign a Name to your run and then construct the FontFamily with the URI constructor:

Xaml:

<Run x:Name="MyTextRun">ABC</Run>

Code behind:

MyTextRun.FontFamily = new FontFamily(new Uri("/FontLibrary;Component/#Kootenay", UriKind.RelativeOrAbsolute), "Kootenay");
MyTextRun.FontSize = 36;

Upvotes: 7

Related Questions