#816 – Using a Font Dialog to Select Fonts
May 9, 2013 1 Comment
Unlike Windows Forms, WPF does not include its own font selection dialog to allow users to pick fonts. You can create your own dialog for this purpose, or you can use a font picker that someone else has developed. (E.g. This one at Codeproject).
You can also just use the Windows Forms FontDialog class directly from WPF.
For example:
<TextBlock Name="tbSomeText" Text="Little Lord Fauntleroy" FontSize="16" Margin="10"/> <Button Content="Click to Choose" HorizontalAlignment="Center" Padding="10,5" Margin="10" Click="Button_Click"/>
In the code-behind, you use a FontDialog instance and then convert the selected font to the properties that you need in WPF.
private void Button_Click(object sender, RoutedEventArgs e) { FontDialog fd = new FontDialog(); System.Windows.Forms.DialogResult dr = fd.ShowDialog(); if (dr != System.Windows.Forms.DialogResult.Cancel) { tbSomeText.FontFamily = new System.Windows.Media.FontFamily(fd.Font.Name); tbSomeText.FontSize = fd.Font.Size * 96.0 / 72.0; tbSomeText.FontWeight = fd.Font.Bold ? FontWeights.Bold : FontWeights.Regular; tbSomeText.FontStyle = fd.Font.Italic ? FontStyles.Italic : FontStyles.Normal; } }
You’ll also need to add a reference to the System.Windows.Forms assembly.