views:

331

answers:

1

Hi 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

+2  A: 

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));
}
Conan
Precisely what I was looking for.. very neat. thanks Conan.
AJ