A Closer Look at Styles and Control Templates
(Page 1 of 4 )
Picking up from where we left off last week, you'll learn how to override style properties, set styles programmatically, and more. 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). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Overriding Style Properties
Further, if we want to override a style property on a specific instance, we can do so by setting the property on the instance, as in Example 5-12.
Example 5-12. Overriding the FontWeight property from the style
<Style x:Key="CellTextStyle">
<Setter Property="TextElement.FontSize" Value="32" />
<Setter Property="TextElement.FontWeight" Value="Bold" />
</Style>
...
<TextBlock
Style="{StaticResource CellTextStyle}"
FontWeight="Thin" ... />
In Example 5-12, the TextBlock instance property setting of FontWeight take precedence over the style property settings of FontWeight.
Inheriting Style Properties
To complete the object-oriented triumvirate of reuse, override, and inheritance, you can inherit a style from a base style, adding new properties or overriding existing ones, as in Example 5-13.
Example 5-13. Style inheritance
<Style x:Key="CellTextStyle">
<Setter Property="TextElement.FontSize" Value="32" />
<Setter Property="TextElement.FontWeight" Value="Bold" />
</Style>
<Style x:Key="StatusTextStyle" BasedOn="{StaticResource CellTextStyle}">
<Setter Property="TextElement.FontWeight" Value="Thin" />
<Setter Property="TextElement.Foreground" Value="White" />
<Setter Property="TextBlock.HorizontalAlignment" Value="Center" />
</Style>
TheBasedOnstyle attribute is used to designate the base style. In Example 5-13, theStatusTextStyle style inherits all of theCellTextStyleproperty setters, overrides theFontWeight, and adds setters forForeground andHorizontalAlignment. Notice that theHorizontalAlignmentproperty uses aTextBlockprefix; this is becauseTextElementdoesn’t have aHorizontalAlignmentproperty.
Our current use of styles causes our tic-tac-toe game to look like Figure 5-4.

Figure 5-4. A tic-tac-toe game with more style
Our application so far is pretty good, especially with the thin font weight on the status text, but we can do better.
Next: Setting Styles Programmatically >>
More XML Articles
More By O'Reilly Media
|
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.
|
|