Given a UIElementCollection, find all the elements that have a StyleA and change them to StyleB in WPF

I have a MyGrid.Children UIElementCollection, I would like to find all the Rectangles in it that have styles set to StyleA and set them to StyleB.

I would like to use LINQ if possible, so I can avoid an unpleasant nested loop.

Something like this pseudo code:

var Recs = from r in MyGrid.Children where r.Style == StyleA && r.GetType() == typeof(Rectangle) select r as Rectangle; 

then

 foreach(Rectangle r in Recs) r.Style = StyleB; 

Does a LINQ Guru Help Improve My LINQ-fu?

+6
linq styles wpf uielementcollection
source share
1 answer

Your code was almost right, but UIElements did not have the Style property ... You can filter the children of the grid by type:

 var recs = from r in MyGrid.Children.OfType<Rectangle>() where r.Style == StyleA select r; foreach(Rectangle r in recs) r.Style = StyleB; 
+15
source share

All Articles