Skip to Main Content
Programming WPF, 2nd Edition
book

Programming WPF, 2nd Edition

by Chris Sells, Ian Griffiths
August 2007
Intermediate to advanced content levelIntermediate to advanced
864 pages
25h 52m
English
O'Reilly Media, Inc.
Content preview from Programming WPF, 2nd Edition

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 style ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming C#, 4th Edition

Programming C#, 4th Edition

Jesse Liberty
Programming C# 10

Programming C# 10

Ian Griffiths

Publisher Resources

ISBN: 9780596510374Supplemental ContentErrata Page