4

我有一个 3x3 矩阵网格。如果用户在特定单元格上,单击后如何识别单元格坐标?

请指教。谢谢PJ

4

1 回答 1

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));
}
于 2010-01-27T01:50:23.777 回答