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

Styles

One of the major uses for resources is to specify styles. A style is a set of property/value pairs to be applied to one or more elements. For example, recall the two TextBlock controls from our Nickname sample, each of which was set to the same VerticalAlignment (Example 1-33).

Example 1-33. Multiple TextBlock controls with the same settings

<!-- Window1.xaml -->
<Window ...>
  <DockPanel ...>
    <TextBlock ...>
      <TextBlock VerticalAlignment="Center">Name: </TextBlock>
      <TextBox Text="{Binding Path=Name}" />
      <TextBlock VerticalAlignment="Center">Nick: </TextBlock>
      <TextBox Text="{Binding Path=Nick}" />
    </TextBlock>
    ...
  </DockPanel>
</Window>

If we wanted to bundle the VerticalAlignment setting into a style, we could do this with a Style element in a Resources block (Example 1-34).

Example 1-34. An example TextBlock style

<Window ...>
  <Window.Resources>
    ...
    <Style x:Key="myStyle" TargetType="{x:Type TextBlock}">
      <Setter Property="VerticalAlignment" Value="Center" />
      <Setter Property="Margin" Value="2" />
      <Setter Property="FontWeight" Value="Bold" />
      <Setter Property="FontStyle" Value="Italic" />
    </Style>
  </Window.Resources>
  <DockPanel ...>
    <TextBlock ...>
      <TextBlock Style="{StaticResource myStyle}">Name: </TextBlock>
      <TextBox Text="{Binding Path=Name}" />
      <TextBlock Style="{StaticResource myStyle}">Nick: </TextBlock>
      <TextBox Text="{Binding Path=Nick}" />
    </TextBlock>
    ...
  </DockPanel>
</Window>

The Style element is really just a named collection of Setter elements for a specific target ...

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