Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store FontFamily as a StaticResource?

I'm trying to figure out how to set a FontFamily in my App.xaml in such a way that I can declaratively apply that style wherever I need to. In the ResourceDictionary I can apply something like:

<System:Double x:Key="SmallTextSize">10</System:Double>

What I want to do then is something like:

<FontFamily x:Key="MainFont">Wingdings</FontFamily>

But, the only thing I can get to work is an implicit style, which requires a target, and multiple declarations of the font I want to use. I need to be able to apply the style I end up with to the FontFamily property of any control.

Here's the closest I can come presently:

<System:String x:Key="MainFont">Wingdings</System:String>
<Style TargetType="UserControl">
      <Setter Property="FontFamily" Value="{StaticResource MainFont}"></Setter>
</Style>

This implementation doesn't work on something like because it expects MainFont to be a FontFamily, not a string:

<TextBlock Text="{Binding}" Margin="0,0,0,4" FontWeight="Normal" FontFamily="{StaticResource MainFont}" FontSize="14.667" />

How should I handle this? Thanks!

like image 492
Grant H. Avatar asked Jan 17 '13 16:01

Grant H.


1 Answers

Not sure I entirely understand this one exactly, since what I do is;

<FontFamily x:Key="MainFont">WingDings</FontFamily>

If you're talking about then applying it to multiple instances without having to declare it to each one then I would just do like;

<Object>
   <Object.Resources>
      <Style TargetType="TextBlock" BasedOn="{StaticResource YourDefaultTextBlockStyleToInheritOtherProperties}">
         <Setter Property="FontFamily" Value="{StaticResource MainFont}"/>
      </Style>
   </Object.Resources>

   <!-- Your FontFamily automatically gets inherited to all children of the object 
        whether your object is say a Grid, or StackPanel, 
        or even an entire UserControl -->    
   <TextBlock Text="ABCDEFG"/>
   <TextBlock Text="12345"/>
   <TextBlock Text="!()*&@#"/>

</Object>
like image 91
Chris W. Avatar answered Sep 22 '22 23:09

Chris W.