I have the following buttons:
<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>
Whenever pressed, these buttons will call:
private void Button_Click(object sender, RoutedEventArgs e)
My question is how do I retrieve the column and row of the button that's been pressed?
CodePudding user response:
From the documentation of RoutedEventHandler
, which is used for the Click
event:
public delegate void RoutedEventHandler(object sender, RoutedEventArgs e);
sender
- The object where the event handler is attached.
Consequently, cast the sender
parameter to Button
and retrieve the row and column from the attached properties using its wrapper methods 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.
}