我有一个3x3矩阵网格。如果特定单元格上的用户,如何在单击后识别单元格坐标?
请指教。谢谢 PJ
答案 0 :(得分:9)
假设你正在设计一个井字游戏风格的游戏,并且所讨论的网格是标准的WPF网格,我想你最好将控件放在每个单独的单元格中。这样你可以为每个事件挂钩鼠标事件,如下所示:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Grid.Column="0" Grid.Row="0" Click="ButtonClick" />
<Button Grid.Column="1" Grid.Row="0" Click="ButtonClick" />
<Button Grid.Column="2" Grid.Row="0" Click="ButtonClick" />
<Button Grid.Column="0" Grid.Row="1" Click="ButtonClick" />
<Button Grid.Column="1" Grid.Row="1" Click="ButtonClick" />
<Button Grid.Column="2" Grid.Row="1" Click="ButtonClick" />
<Button Grid.Column="0" Grid.Row="2" Click="ButtonClick" />
<Button Grid.Column="1" Grid.Row="2" Click="ButtonClick" />
<Button Grid.Column="2" Grid.Row="2" Click="ButtonClick" />
</Grid>
</Window>
在您的代码隐藏中:
private void ButtonClick(object sender, RoutedEventArgs e)
{
Button _btn = sender as Button;
int _row = (int)_btn.GetValue(Grid.RowProperty);
int _column = (int)_btn.GetValue(Grid.ColumnProperty);
MessageBox.Show(string.Format("Button clicked at column {0}, row {1}", _column, _row));
}