A Closer Look at Styles and Control Templates - Data Templates and Styles
(Page 4 of 4 )
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-tac-toe 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.
Please check back tomorrow 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.
|
|