WPF Styles and Control Templates—Setting Styles Programmatically
| Visual C# Tutorials |
| .NET Framework Tutorials |
| © 2005 O'Reilly Media |
Setting Styles Programmatically
Once a style has a name, it’s easily available from our code. For example, we might
decide that we’d like each player to have their own style. In this case, using named
styles in XAML at compile time won’t do the trick, since we want to set the style
based on the content, which isn’t known until runtime. However, there’s nothing
that requires us to set the Style property of a control statically; we can set it programmatically
as well, as we do in Example 5-14.
Example 5-14. Setting styles programmatically
public partial class Window1 : Window { void cell_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; ... // Set button content button.Content = this.CurrentPlayer; ... if( this.CurrentPlayer == "X" ) { button.Style = (Style)FindResource("XStyle"); this.CurrentPlayer == "O"; } else { button.Style = (Style)FindResource("OStyle"); this.CurrentPlayer == "X"; } ... } ... }
In Example 5-14, whenever the player clicks, in addition to setting the button’s content, we pull a named style out of the window’s resources and use that to set the button’s style. This assumes a pair of named styles defined in the window’s scope, as in Example 5-15.
Example 5-15. Styles pulled out via FindResource
<Window.Resources> <Style x:Key="CellTextStyle"> <Setter Property="TextElement.FontSize" Value="32" /> <Setter Property="TextElement.FontWeight" Value="Bold" /> </Style> <Style x:Key="XStyle" BasedOn="{StaticResource CellTextStyle}"> <Setter Property="TextElement.Foreground" Value="Red" /> </Style> <Style x:Key="OStyle" BasedOn="{StaticResource CellTextStyle}"> <Setter Property="TextElement.Foreground" Value="Green" /> </Style> </Window.Resources>
With these styles in place and the code to set the button style along with content, we get Figure 5-5.
Notice that the Xs and Os are colored according to the named player styles. In this particular case (and in many other cases, too), data triggers (discussed in "Data Triggers," later in this chapter) should be preferred to setting styles programmatically, but you never know when you’re going to have to jam.
As with all XAML constructs, you are free to create styles themselves programmatically. Appendix A is a good introduction on how to think about going back and forth between XAML and code.

Figure 5-5. Setting styles programmatically based on an object’s content (Color Plate 9)
|

