使用 lambda 进行 ObservableCollection 切片
我有 ObservableCollectionViewUnit
实现 INotifyPropertyChanged
。
ViewUnit
具有 Handled : bool
属性。
WPF 应用程序的主视图有一个绑定到 _myItems
的 ListBox
。
我只想要未处理的项目的单独视图,即拥有一个依赖于现有 _myItems
的 IObservableCollection<> 但仅包含已过滤的项目,最好使用拉姆达表达式。
理想情况下,
IObservableCollection<ViewUnit> _myFilteredCollection = HelperClass<ViewUnit>.FromExisting(_myItems, (e) => !e.Handled);
我可以自己实现它。我只是觉得有人解决了这个问题并且有一个很好的解决方案(我只是不知道它的名字)。
I have ObservableCollection<ViewUnit> _myItems
field, where ViewUnit
implements INotifyPropertyChanged
.
ViewUnit
has Handled : bool
property.
The main view of WPF application has a ListBox
which binds to _myItems
.
I want a separate view of non-handled items only, that is, to have an IObservableCollection<>
depended on existing _myItems
but having only filtered items, preferably, using a lambda expression.
Ideally, this would be
IObservableCollection<ViewUnit> _myFilteredCollection = HelperClass<ViewUnit>.FromExisting(_myItems, (e) => !e.Handled);
I could implement it on my own. I just feel somebody though this problem through and has a good solution available (I just don't know its name).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看 CollectionView。这是围绕处理过滤、分组和排序的集合的视图。当您要求 WPF 绑定到集合时,它实际上绑定到其默认视图,因此您可以像这样过滤默认集合视图:
过滤器是
object
上的谓词,因此您必须将参数强制转换为ViewUnit
。如果属性发生变化,它也不会收到通知,因此如果Handled
属性发生变化,您需要调用collectionView.Refresh
。不过,如果您在_myItems
中添加或删除,它将会更新。另请查看 Bea Stollnitz 的博客文章如何从集合中过滤项目。
Take a look at CollectionView. This is a view around a collection that handles filtering, grouping, and sorting. When you ask WPF to bind to a collection it actually binds to its default view, so you can just filter the default collection view like this:
The filter is a predicate on
object
, so you'll have to cast the parameter toViewUnit
. It also won't be notified if the property changes, so you'll need to callcollectionView.Refresh
if theHandled
property changes. It will be updated if you add or remove from_myItems
, though.Also check out Bea Stollnitz's blog entry How do I filter items from a collection.