I am a beginner at using WPF.
I have wrote some xaml code in order to make a tic tac toe game.
I have a grid with 3 x 3 cells. I have put a button inside each cell of the grid.
I want to print out the position of the button with respect to the grid(ie row number and column number) when I press the button.
This is the xaml code :
<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>
This is the C# code :
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;
}
}
}
}
Inside the button_Click
method I want to print the row number and column number of the grid, where that button is placed. How can I obtain that information?
You may get the row and column index by these static methods of Grid:
int row = Grid.GetRow(b);
int column = Grid.GetColum(b);
The methods return the values of the attached properties Grid.Row
and Grid.Column
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.