Styles and Control Templates - Named Styles
(Page 4 of 4 )
WPF’s ability to apply styles to objects that don’t have all of the properties defined in the style is analogous to applying the Word Normal style, which includes a font size property of its own, to both a range of text and an image. Even though Word knows that images don’t have a font size, it applies the portions of the Normal style that do make sense (such as the justification property), ignoring the rest.
Getting back to our sample, we can use theCellTextStyleon aTextBlockin a new row to show whose turn it is, as in Example 5-11.
Example 5-11. Applying a style to Button and TextBlock elements
<Window.Resources>
<Style x:Key="CellTextStyle">
<Setter Property="TextElement.FontSize" Value="32" />
<Setter Property="TextElement.FontWeight" Value="Bold" />
</Style>
</Window.Resources>
<Grid Background="Black">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button Style="{StaticResource CellTextStyle}" ... />
...
<TextBlock
Style="{StaticResource CellTextStyle}"
Foreground="White"
Grid.Row="3"
Grid.ColumnSpan="3"
x:Name="statusTextBlock" />
</Grid>
</Window>
This reuse of the style across controls of different types gives me a consistent look in my application, as shown in Figure 5-3.
One thing you’ll notice is that the status text in Figure 5-3 is white, while the text in the buttons is black. Since black is the default text color, if we want the status text to show up against a black background, we have to change the color to something else, hence the need to set theForegroundproperty to white on theTextBlock. Setting per-instance properties works just fine in combination with the style, and you can
combine the two techniques of setting property values as you see fit.

Figure 5-3. A tic-tac-toe game with style
Please check back next week for the continuation of this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter five of the book Programming Windows Presentation Foundation, written by Chris Sells and Ian Griffiths (O'Reilly; ISBN: 0596101139). Check it out today at your favorite bookstore. Buy this book now.
|
|