Named Styles

By hoisting the same inline style into a resource (as introduced in Chapter 1), we can award it a name and use it by name in our button instances, as shown in Example 8-5.

Example 8-5. Setting a named style

<!-- Window1.xaml -->
<Window ...>
  <Window.Resources>
    <Style x:Key="CellTextStyle">
      <Setter Property="Control.FontSize" Value="32pt" />
      <Setter Property="Control.FontWeight" Value="Bold" />
    </Style>
  </Window.Resources>
  ...
  <Button Style="{StaticResource CellTextStyle}" ... Name="cell00" />
  ...
</Window>

In Example 8-5, we've used the class name as a prefix on our properties so that the style knows what dependency property we're talking about. We used Control as the prefix instead of Button to allow the style to be used more broadly, as we'll soon see.

The Target Type Attribute

As a convenience, if all of the properties can be set on a shared base class, like Control in our example, we can promote the class prefix into the TargetType attribute and remove it from the name of the property (see Example 8-6).

Example 8-6. A target-typed style

<Style x:Key="CellTextStyle" TargetType="{x:Type Control}">
  <Setter Property="FontSize" Value="32pt" />
  <Setter Property="FontWeight" Value="Bold" />
</Style>

When providing a TargetType attribute, you can only set properties available on that type. If you'd like to expand to a greater set of properties down the inheritance tree, you can do so by using a more derived type (see Example 8-7).

Example 8-7. A more derived target-typed ...

Get Programming WPF, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.