How To Globally Specify FontFamily In WPF?

|

This question is asked about seven months ago in WPF MSDN forum, From the begining, I think this should be obvious, just specify the TextElement.FontFamily in the Application level, the font shall be applied to the entire UI elements within the app:

<Application TextElement.FontFamily="Constantia"/>

But the thing is not that so straightforward, since Application is not a DependencyObject, you cannot specify an attached property on it, then how to do this trick?

Just recently, I come up with an approach, since nearly every WPF UI control hosts TextBlock inside (either in data template or control template) to display text (except FlowDocument, FlowDocument has a different mechanism to render text), I can specify a Style within Application.Resources for TextBlock, then the style shall be applied to each TextBlocks within the app:

<Application x:Class="GlobalFontSettings.App"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   StartupUri="Window1.xaml">
  <
Application.Resources>
    <
Style TargetType="{x:Type TextBlock}">
      <
Setter Property="TextElement.FontFamily" Value="Constantia"/>
    </
Style>
  </
Application.Resources>
</
Application>

    

I've written a little test app for it, and it works like a charm, hope this can help others who also want to implement the similar thing in WPF.

3 comments:

Anonymous said...

Thank you !

NT said...

Great stuff.

Anonymous said...

Seems like a neat solution.

Thank you, that helped me a lot! ; )