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.