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!
views:
1917answers:
3
A:
This answer will help you
int rowIndex = Grid.GetRow(myButton);
RowDefinition rowDef = myGrid.RowDefinitions[rowIndex];
Carlo
2009-10-02 21:10:42
Thanks, but it doesn't do the job because I don't have a reference to myButton!
Mathias
2009-10-02 21:14:47
Oh I understand.
Carlo
2009-10-02 21:17:22
+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
2009-10-02 21:12:19
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
2009-10-02 21:16:11
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
2009-10-02 21:17:20
Thanks, Reed, good point -- that can easily be accomplished by using Where instead of First.
itowlson
2009-10-02 21:19:24
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
2009-10-02 21:17:38