views:

730

answers:

1

I'd like to give every Control a certain FontFamily and FontWeight in Silverlight 4.0. I know that styles can now apply to all controls of a certain type, so I tried this:

<Style TargetType="Control">
    <Setter Property="FontFamily" Value="Arial" />
    <Setter Property="FontWeight" Value="Bold" />
</Style>

Unfortunately, that doesn't appear to work. I can do this for types that derive from Control, however. For example, setting TargetType to Button applies those values to every Button in my application.

Why can't I do this for the Control base class, then?

+2  A: 

The control styling being tied to the type system can be a bit misleading. Its actually based on the value of the controls DefaultStyleKey property. In the case of a Button the value is typeof(Button) and for a TextBox it is typeof(Textbox).

A default style will be applied to a control if the TargetType value equals the controls DefaultStyleKey value. There is no examination of whether the Type in the DefaultStyleKey is a derivative of the TargetType.

Font related properties are a special case since most controls will inherit the values for Font properties from the containing context. Hence you can effectively acheive the same result by specifying FontFamily and FontWeight on the UserControl element.

Edit

From a comment by the OP:-

I was hoping that I could set it in one place and have every UserControl in the entire application take on that style.

The closest you can get to that is to place a keyed style in the app resources and ensure all the usercontrols bind to that style. Of course this still requires some co-operation for each user control but at least the font choices remain in a single place.

For example in app.xaml:-

<Style x:Key="Common" TargetType="UserControl">
 <Setter Property="FontFamily" Value="Arial" />
 <Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="Blue" />

Then in each usercontrol:-

<UserControl ...namespace stuff here...
   Style="{StaticResource Common}">
  <!-- ... content here ... -->
AnthonyWJones
Thanks, that makes sense. Although I was hoping that I could set it in one place and have every UserControl in the entire application take on that style. I guess I could make a custom UserControl to base the others on, though.
David Brown