我是使用WPF的初学者。
我已经写了一些xaml代码来制作一个tic tac toe游戏。
我的网格有3 x 3个单元格。我在网格的每个单元格中放了一个按钮。
我想在按下按钮时打印按钮相对于网格的位置(即行号和列号)。
这是xaml代码:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test Window" Height="500" Width="500" BorderBrush="#FA0D0D0D">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button Name ="b1" Grid.Column=" 0" Grid.Row=" 0" Click="button_Click" />
<Button Name ="b2" Grid.Column=" 0" Grid.Row=" 1" Click="button_Click" />
<Button Name ="b3" Grid.Column=" 0" Grid.Row=" 2" Click="button_Click" />
<Button Name ="b4" Grid.Column=" 1" Grid.Row=" 0" Click="button_Click" />
<Button Name ="b5" Grid.Column=" 1" Grid.Row=" 1" Click="button_Click" />
<Button Name ="b6" Grid.Column=" 1" Grid.Row=" 2" Click="button_Click" />
<Button Name ="b7" Grid.Column=" 2" Grid.Row=" 0" Click="button_Click" />
<Button Name ="b8" Grid.Column=" 2" Grid.Row=" 1" Click="button_Click" />
<Button Name ="b9" Grid.Column=" 2" Grid.Row=" 2" Click="button_Click" />
</Grid>
</Window>
这是C#代码:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
static int symbol;
static int[][] game;
public MainWindow()
{
InitializeComponent();
symbol = 1;
game = new int[3][];
game[0] = new int[3];
game[1] = new int[3];
game[2] = new int[3];
}
private void button_Click(object sender, RoutedEventArgs e)
{
Button b = (Button)sender;
if (symbol == 1)
{
b.Content = "x";
symbol = 2;
}
else
{
b.Content = "o";
symbol = 1;
}
}
}
}
在button_Click
方法中,我想打印网格的行号和列号,放置该按钮。我怎样才能获得这些信息?
答案 0 :(得分:3)
您可以通过Grid的这些静态方法获取行和列索引:
int row = Grid.GetRow(b);
int column = Grid.GetColum(b);
这些方法会返回attached properties Grid.Row
和Grid.Column
的值。