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 his own style:

<Style x:Key="XStyle" BasedOn="{StaticResource CellTextStyle}"> <Setter Property="Control.Foreground" Value="Red" />

<Style x:Key="OStyle" BasedOn="{StaticResource CellTextStyle}"> <Setter Property="Control.Foreground" Value="Green" />

In this case, applying named styles to each button in XAML at compile time won't do the trick, because we want to set the style based on the content, and in this application, the content changes when a button is clicked at runtime. However, nothing requires us to set the Style property of a control statically; we can set it programmatically as well, as we do in Example 8-12.

Example 8-12. Setting styles programmatically public partial class Window1 : Window {

void cell_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender;

Example 8-12. Setting styles programmatically (continued)

// Set button content button.Content = this.CurrentPlayer;

if( this.CurrentPlayer == "X" ) { button.Style = (Style)FindResource("XStyle");

this.CurrentPlayer == "O";

button.Style = (Style)FindResource("OStyle");

this.CurrentPlayer == "X";

In Example 8-12, whenever the player clicks, in addition to setting the button's content, we pull a named style out of the window's resources with the FindResource method and use that to set the button's style, as shown in Figure 8-5.

Figure 8-5. Setting styles programmatically based on an object's content (Color Plate 7)

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 should be preferred to setting styles programmatically, but we'll get to that later.

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.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment