How to get controls from Grid.Row at runtime?
I have a Grid
with 3 Rectangle
s开发者_如何学运维 in it. I need to get a reference to the rectangle that has Grid.Row == 3
at runtime.
How can I get access to it?
Thanks
var target = myGrid.Children
.Cast<UIElement>() // make it into IEnumerable<UIElement>
.OfType<Rectangle>() // and select only Rectangles
.Where(c => Grid.GetRow(c) == 3);
This will enumerate the children of your grid, and select only those which are of type Rectangle
and have Grid.Row
== 3. You can then use target.Single()
or target.First()
or any other query evaluation function to get access to the Rectangle
.
Update:
Updated to address Ian's comment below. Very well said, I fully agree (didn't give too much thought to the original example code).
精彩评论