Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to identify which cell was clicked on WPF Grid?

Tags:

c#

wpf

cell

grid

I have a 3x3 matrix grid. If a user on particular cell, how can I identify the cell cordinates after click?

Please advise. thanks PJ

like image 632
AJ. Avatar asked Jan 23 '23 16:01

AJ.


1 Answers

Assuming you're designing a tic-tac-toe style game, and the grid in question is the standard WPF Grid, I'd imagine you'd be best putting a control in each separate cell. That way you can hook into mouse events for each, like so:

<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>

And in your code-behind:

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));
}
like image 57
Conan Avatar answered Jan 31 '23 21:01

Conan