tags:

views:

1917

answers:

3

Once Controls have been added to a WPF Grid, is there a way to programmatically access them by row & column index? Something along the lines of
var myControl = (object)MyGrid.GetChild(int row, int column);
... where GetChild is the method I wish I had!

A: 

This answer will help you

int rowIndex = Grid.GetRow(myButton);

RowDefinition rowDef = myGrid.RowDefinitions[rowIndex];
Carlo
Thanks, but it doesn't do the job because I don't have a reference to myButton!
Mathias
Oh I understand.
Carlo
+5  A: 

There isn't a built-in method for this, but you can easily do it by looking in the Children collection:

myGrid.Children
      .Cast<UIElement>()
      .First(e => Grid.GetRow(e) == row && Grid.GetColumn(e) == column);
itowlson
+1 Clever solution
Reed Copsey
Although - It might be worth returning the full collection, since technically, you can have more than one element in a single grid "cell", since hte attached properties don't check for that.
Reed Copsey
Thank you. That is the approach I have been following so far, iterating over every child in Children until I find one control with matchin row and column, but I expected there would be something more direct.
Mathias
Thanks, Reed, good point -- that can easily be accomplished by using Where instead of First.
itowlson
A: 

The Children property of the grid object will give you a collection of all the children of the Grid (from the Panel class).

As far as getting the coordinates in the grid, look at the static methods in the Grid class (GetRow() & GetColumn()).

Hope that sets you off in the right direction.

Eric