August 2007
Intermediate to advanced
864 pages
25h 52m
English
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 ...