首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WPF 樣式入門:從井字遊戲看不使用樣式的維護困境

     編輯:關於.NET

井字遊戲的初始實作:完全無樣式的版本

為了展示樣式在 WPF 中的重要性,我們以一個簡單的井字遊戲為例。以下是完全不使用樣式的 XAML 實作,使用 Grid 排列 9 個按鈕組成 3x3 棋盤:

範例 5-1:Window1.xaml

<Window x:Class="TicTacToe.Window1"
        xmlns="https://schemas.microsoft.com/winfx/avalon/2005"
        xmlns:x="https://schemas.microsoft.com/winfx/xaml/2005"
        Title="TicTacToe">
  <Grid Background="Black">
    <Grid.RowDefinitions>
      <RowDefinition /><RowDefinition /><RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition /><ColumnDefinition /><ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Button Margin="0,0,2,2" Grid.Row="0" Grid.Column="0" x:Name="cell00" />
    <Button Margin="2,0,2,2" Grid.Row="0" Grid.Column="1" x:Name="cell01" />
    <Button Margin="2,0,0,2" Grid.Row="0" Grid.Column="2" x:Name="cell02" />
    <Button Margin="0,2,2,2" Grid.Row="1" Grid.Column="0" x:Name="cell10" />
    <Button Margin="2,2,2,2" Grid.Row="1" Grid.Column="1" x:Name="cell11" />
    <Button Margin="2,2,0,2" Grid.Row="1" Grid.Column="2" x:Name="cell12" />
    <Button Margin="0,2,2,0" Grid.Row="2" Grid.Column="0" x:Name="cell20" />
    <Button Margin="2,2,2,0" Grid.Row="2" Grid.Column="1" x:Name="cell21" />
    <Button Margin="2,2,0,0" Grid.Row="2" Grid.Column="2" x:Name="cell22" />
  </Grid>
</Window>

黑色背景配合按鈕間的間距,形成類似手繪棋盤的交叉線效果。遊戲邏輯在代碼後置檔案中實作,使用字串追蹤當前玩家(X 或 O),按鈕陣列追蹤格子狀態。

範例 5-2:遊戲邏輯實作

public partial class Window1 : Window {
  string currentPlayer;
  Button[] cells;

  public Window1() {
    InitializeComponent();
    this.cells = new Button[] { this.cell00, this.cell01, ... };
    foreach (Button cell in this.cells) {
      cell.Click += cell_Click;
    }
    NewGame();
  }
  // ... 遊戲邏輯:NewGame、cell_Click、HasWon、TieGame 等方法
}

視覺調整的維護噩夢

執行畫面顯示棋盤背景來自頁面空白,看似手繪木板,但按鈕上的 X 和 O 字體大小未與線條粗細匹配。若要修正,最直接的方式是為每個按鈕單獨設定字體屬性:

範例 5-3:逐個設定按鈕字體

<Button FontSize="32" FontWeight="Bold" x:Name="cell00" />
<Button FontSize="32" FontWeight="Bold" x:Name="cell01" />
<Button FontSize="32" FontWeight="Bold" x:Name="cell02" />
...(共 9 個按鈕)

雖然視覺效果改善了,但未來若要調整字體大小或粗細,必須修改 9 個獨立位置的程式碼。這種重複性工作違反了程式設計的「不要重複自己」原則,也增加了維護成本與出錯風險。我們真正需要的是將所有棋盤格子的外觀定義集中在一個共同的地方——這正是樣式機制派上用場的時刻。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved