Data Templates and Styles

Let's imagine that we want to implement a variant of tic-tac-toe that's more fun to play (an important feature in most games). For example, one variant of tic-tac-toe only allows players to have 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, with each move represented by a PlayerMove object, as shown in Example 8-19.

Example 8-19. A custom type suitable for tracking tic-tac-toe moves public class PlayerMove : INotifyPropertyChanged { string playerName; public string PlayerName { get { return playerName; } set {

if( string.Compare(playerName, value) == 0 ) { return; }

playerName = value;


int moveNumber; public int MoveNumber { get { return moveNumber; }

moveNumber = value;


Example 8-19. A custom type suitable for tracking tic-tac-toe moves (continued)

bool isPartOfWin = false; public bool IsPartOfWin { get { return isPartOfWin; } set {

if( isPartOfWin == value ) { return; } isPartOfWin = value; Notify("IsPartOfWin");

public PlayerMove(string playerName, int moveNumber) { this.playerName = playerName; this.moveNumber = moveNumber;

// INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; void Notify(string propName) { if( PropertyChanged != null ) { PropertyChanged(this, new PropertyChangedEventArgs(propName));

Now, instead of using a simple string for each button object's content, we'll use an instance of PlayerMove, as shown in Example 8-20.

Example 8-20. Adding the PlayerMove as Button content namespace TicTacToe { public partial class Windowl : 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 8-8 shows the brilliance of such a change (after turning off the button style so that the text isn't too large to read).

0 TirTarTrv 1 = 10: £3 |1


Tic TacTof. PlayerMove

f ic F ac Too.Pljycr Move

1 KÎiJt foc.i'lüyui Move


It's your turn, 0

Figure 8-8. PlayerMove objects displayed without any special instructions

As you'll recall from Chapter 6, in Figure 8-8 the button doesn't have enough information to render a PlayerMove object, but we can fix that with a data template.

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