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

跟風遠走 提交于 2019-12-04 08:42:05

问题


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

I'd like to use LINQ if possible, so I can avoid a nasty nested loop.

Something like this pseudocode:

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;

Can a LINQ guru help me improve my LINQ-fu?


回答1:


Your code was almost correct, but UIElements don't have a Style property... You can filter the grid's children based to their type :

var recs = from r in MyGrid.Children.OfType<Rectangle>()
           where r.Style == StyleA
           select r;

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


来源:https://stackoverflow.com/questions/2337421/given-uielementcollection-find-all-elements-that-have-stylea-and-change-them-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!