开发者

ObservableCollection slicing using lambda

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<ViewUn开发者_开发问答it> _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).


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:

var collectionView = CollectionViewSource.GetDefaultView(_myItems);
collectionView.Filter = e => !((ViewUnit)e).Handled;

The filter is a predicate on object, so you'll have to cast the parameter to ViewUnit. It also won't be notified if the property changes, so you'll need to call collectionView.Refresh if the Handled 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜