首页 > 解决方案 > 如何在 ItemCollection 中找到具有特定属性的项目?

问题描述

我有一个带有不同类型 UserControls 的 ItemsCollection,需要查找是否有任何对象满足条件Any(p => p.GotFocus)。由于 ItemsCollection 没有实现 IEnumerable,因此我可以将集合转换为某种类型,如ItemCollection 的基本 LINQ 表达式中所述:

bool gotFocus = paragraphsItemControl.Items.Cast<ParagraphUserControl>().Any(p => p.GotFocus);

该集合由不同类型的 UserControls 组成(虽然每个都继承自同一个父级),所以如果我强制转换为特定类型,则会引发异常。如何查询 UserControl 对象的集合?

标签: c#wpfitemcollection

解决方案


使用OfType()而不是Cast()

bool gotFocus = paragraphsItemControl.Items
     .OfType<ParagraphUserControl>().Any(p => p.GotFocus);

但请注意,这只会ParagraphUserControl检查类型的控件。

假设所有控件都继承自ParentParent具有GotFocus属性,然后检查所有控件,您可以这样做:

bool gotFocus = paragraphsItemControl.Items
     .Cast<Parent>().Any(p => p.GotFocus);

推荐阅读