【问题标题】:How to identify position of a button with respect to a grid which contains a set of buttons如何识别按钮相对于包含一组按钮的网格的位置
【发布时间】:2013-06-28 00:13:06
【问题描述】:

我是使用 WPF 的初学者。

为了制作井字游戏,我编写了一些 xaml 代码。

我有一个 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 方法中,我想打印放置该按钮的网格的行号和列号。我怎样才能获得这些信息?

【问题讨论】:

    标签: wpf wpf-controls


    【解决方案1】:

    您可以通过 Grid 的这些静态方法获取行和列索引:

    int row = Grid.GetRow(b);
    int column = Grid.GetColum(b);
    

    这些方法返回 attached properties Grid.RowGrid.Column 的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多