【问题标题】:How do I find items with specific property in an ItemCollection?如何在 ItemCollection 中找到具有特定属性的项目?
【发布时间】:2019-04-07 18:00:39
【问题描述】:

我有一个带有不同类型用户控件的 ItemsCollection,需要查找是否有任何对象满足条件Any(p => p.GotFocus)。由于 ItemsCollection 没有实现 IEnumerable,我可以将集合转换为某种类型,如 Basic LINQ expression for an ItemCollection 中所述,如下所示:

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

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

【问题讨论】:

    标签: c# wpf itemcollection


    【解决方案1】:

    使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多