讓我們想象一下我們想要實作TTT更有娛樂性的一個版本(這是大部分遊戲中最重要的特色)。例如,TTT的一種變體允許玩家每次隻能占據3個格子,去除第一步在下第四步的時候,去除第二步在下第五步的時候,,以此類推。為了實作這個變體,我們需要保持對每一步按順序跟蹤——可以利用PlayMover類,如示例5-20。
示例5-20
namespace TicTacToe
{
public class PlayerMove
private string playerName;
public string PlayerName
get
{ return playerName; }
set
{ playerName = value; }
}
private int moveNumber;
public int MoveNumber
{ return moveNumber; }
{ moveNumber = value; }
public PlayerMove(string playerName, int moveNumber)
this.playerName = playerName;
this.moveNumber = moveNumber;
}
}
現在,取代以為每個按鈕對象的内容使用一個簡單的字元串,我們将用示例
5-20中的一個PlayMover執行個體鮮明顯示這樣的一個改動。
示例5-21
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);
圖
5-6
正如你回想到的,在第四章,圖5-6所發生的是,按鈕沒有足夠多的資訊生成一個PlayMover對象,但是我們可以通過一個資料模闆修複它。
5.5.1資料模闆
回憶第四章,WPF允許你定義一個資料模闆,這是一棵元素樹,可以在特定的上下文中擴充。資料模闆用于提供一個應用程式生成非可視化外觀對象的能力,正如示例5-22所示。
示例5-22
<?Mapping XmlNamespace="l" ClrNamespace="TicTacToe" ?>
<Window
xmlns:local="local">
<Window.Resources>
<DataTemplate DataType="{x:Type local:PlayerMove}">
<Grid>
<TextBlock
TextContent="{Binding Path=PlayerName}"
FontSize ="32"
FontWeight="Bold"
VerticalAlignment="Center"
HorizontalAlignment="Center" />
TextContent="{Binding Path=MoveNumber}"
FontSize="16"
FontStyle="Italic"
VerticalAlignment="Bottom"
HorizontalAlignment="Right" />
</Grid>
</DataTemplate>
</Window.Resources>
</Window>
使用在第一章介紹的
xaml映射文法,我們将PlayMover類型間接映射到了帶有xmlns屬性的xaml中,我們将其作為資料模闆的資料類型。現在,無論何時WPF遇到一個PlayMove對象,如我們所有的按鈕内容,資料模闆都會展開。在我們這種情形,這個模闆由一個grid組成,其中排列了兩個TextBlock,一個在按鈕中間顯示玩家名,另一個在按鈕右下位置顯示移動的步數,伴随着其它的一些設定使之看起來更漂亮。
5.5.2帶樣式的資料綁定
盡管如此,這些屬性設定深埋在資料模闆的很深層。正像這是一個好的想法将“魔力數字”移出你的代碼,将它們拉出去并給它們一個易于管理的名稱,這是一個好的想法将成組的設定移動到樣式中,如示例5-23所示。
*将成組的設定移動到樣式中,還顧及皮膚和主題,在第六章會介紹。
示例5-23
<Window.Resources>
<Style x:Key="CellTextStyle" TargetType="{x:Type TextBlock}">
<Setter Property="FontSize" Value="32" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
<Style x:Key="MoveNumberStyle" TargetType="{x:Type TextBlock}">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontStyle" Value="Italic" />
<Setter Property="VerticalAlignment" Value="Bottom" />
<Setter Property="HorizontalAlignment" Value="Right" />
<DataTemplate DataType="{x:Type l:PlayerMove}">
<Grid>
<TextBlock
TextContent="{Binding Path=PlayerName}"
Style="{StaticResource CellTextStyle}" />
TextContent="{Binding Path=MoveNumber}"
Style="{StaticResource MoveNumberStyle}" />
</Grid>
</DataTemplate>
</Window.Resources>
使用樣式是很通常的,進而可以使用資料模闆設定成組的屬性,建立帶有大量屬性的大量元素。圖
5-7顯示了這個結果。
圖5-7
仍然,像圖5-7一樣漂亮,互動作用是一種WPF給予的令人厭煩的能力。讓我們看一下使用在應用程式中使用樣式屬性我們都能做些什麼。