views:

43

answers:

1

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).

+4  A: 

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.

Quartermeister
It's important to note that a CollectionView created from an ObservableCollection raises events properly. That's a really significant strength.
Robert Rossney