获取按下按钮的网格行和网格列

Get Grid Row and Grid column of button pressed

我有以下按钮:

<Button Grid.Row="0" Grid.Column="0" FontSize="48"></Button>
<Button Grid.Row="1" Grid.Column="0" FontSize="48"></Button>
<Button Grid.Row="2" Grid.Column="0" FontSize="48"></Button>
<Button Grid.Row="0" Grid.Column="1" FontSize="48"></Button>
<Button Grid.Row="0" Grid.Column="2" FontSize="48"></Button>
<Button Grid.Row="1" Grid.Column="1" FontSize="48"></Button>
<Button Grid.Row="1" Grid.Column="2" FontSize="48"></Button>
<Button Grid.Row="2" Grid.Column="1" FontSize="48"></Button>
<Button Grid.Row="2" Grid.Column="2" FontSize="48"></Button>

无论何时按下,这些按钮都会调用:

private void Button_Click(object sender, RoutedEventArgs e)

我的问题是如何检索按下的按钮的列和行?

来自 RoutedEventHandler 的文档,用于 Click 事件:

public delegate void RoutedEventHandler(object sender, RoutedEventArgs e);

sender - The object where the event handler is attached.

因此,将 sender 参数转换为 Button 并使用其包装方法 Grid.GetRow(...) and Grid.GetColumn(...).

从附加属性中检索行和列
private void Button_Click(object sender, RoutedEventArgs e)
{
   var button = (Button)sender;
   var row = Grid.GetRow(button);
   var column = Grid.GetColumn(button);

   // ...other code.
}