WPF Styles and Control Templates—Data Templates and Styles
| Visual C# Tutorials |
| .NET Framework Tutorials |
|
WPF Styles and Control Templates
|
| © 2005 O'Reilly Media |
Data Templates and Styles
Let’s imagine that we wanted to implement a version of tic-tac-toe that’s more fun to
play (that’s an important feature in most games). For example, one variant of tic-tactoe
allows players to have only three of their pieces on at any one time, dropping the
first move off when the fourth move is played, dropping the second move when the
fifth is played, and so on. To implement this variant, we need to keep track of the
sequence of moves, which we can do with a PlayerMove class, as in Example 5-20.
Example 5-20. A custom type suitable for tracking tic-tac-toe moves
namespace TicTacToe { public class PlayerMove { private string playerName; public string PlayerName { get { return playerName; } set { playerName = value; } } private int moveNumber; public int MoveNumber { get { return moveNumber; } set { moveNumber = value; } } public PlayerMove(string playerName, int moveNumber) { this.playerName = playerName; this.moveNumber = moveNumber; } } }
Now, instead of using a simple string for each of the button object’s content, we’ll
use an instance of PlayerMove in Example 5-21. Figure 5-6 shows the brilliance of
such a change.
Example 5-21. Adding the PlayerMove as Button content
namespace TicTacToe { public partial class Window1 : Window { ... int moveNumber; void NewGame( ) { ... this.moveNumber = 0; } void cell_Click(object sender, RoutedEventArgs e) { ... // Set button content //button.Content = this.CurrentPlayer; button.Content = new PlayerMove(this.CurrentPlayer, ++this.moveNumber); ... } ... } }

Figure 5-6. PlayerMove objects displayed without any special instructions
As you’ll recall from Chapter 4, what’s happening in Figure 5-6 is that the button
doesn’t have enough information to render a PlayerMove object, but we can fix that
with a data template.
|

