Home > View Post

Determining row and column of a grid click

One of the delegates at FEST '08 asked me if there was an easy way to determine the cell (row and column) of a click received by a grid in WPF. A little investigation proved there's no easy way to do this. That is there aren't any GridClickEventArgs with a row and column property.

However, it's not too hard to put together a solution for this and somebody at Microsoft kindly shared a (rather elegant) function they'd used before for this.

private void GetGridColumnAndRow(Grid grid, Point p, out int column, out int row)
{
     for (column = 0; column < grid.ColumnDefinitions.Count; column++)
     {
            p.X -= grid.ColumnDefinitions[column].ActualWidth;
            if (p.X < 0)
            {
                 break;
            }
     }
     for (row = 0; row < grid.RowDefinitions.Count; row++)
     {
            p.Y -= grid.RowDefinitions[row].ActualHeight;
            if (p.Y < 0)
            {
                 break;
            }
     }
}

I though I'd post it here in case I need it again or anybody else out there wants to use it.

Tags: WPF

 
Josh Post By Josh Twist
12:10 AM
20 Jun 2008

» Next Post: What's next for Ukadc.Diagnostics?
« Previous Post: Thanks to NxtGenUG - WPF and Databinding bits and pieces

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.