Yanshof
Yanshof

Reputation: 9926

How to get controls from Grid.Row at runtime?

I have a Grid with 3 Rectangles 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

Upvotes: 0

Views: 1925

Answers (1)

Jon
Jon

Reputation: 437396

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).

Upvotes: 5

Related Questions