Wpf has great filtering capabilities based on CollectionViewSource class, but how can we use effectively in MVVM architecture? First of all we need to decide who has the responsibility of filtering data, and clearly the answer is: the ViewModel. VM usually exposes an ObservableCollection<T> property for collections of items, the view bind to it and everything goes smooth, until you need to set a filter on it. A possible solution is to grab a reference to an ICollectionView in the viewmodel and manipulate that object
I do not like very much this approach, are you sure that a valid default view exists during a UnitTest? So lets examine another possible solution.
Suppose you have a view that has a ListView currently bound to a property of ViewModel called Links, and this property is an ObservableCollection<T>, suppose also that you need to filter content based on a property called Status. What I want is â€œno codeâ€ on the View, and minimum impact on the already existing view, I want also the ability to test the filter function with a unit test.
For the first requirements, it is enough to expose to the view â€œsomethingâ€ bindable in the same property name (Links), since my ViewModel has an ObservableCollection<SingleAnalysisLink> called Links, I changed the viewmodel in this way.
The real ObservableCollection is now internal, then I added a CollectionViewSource property and finally the Links readonly property that return the View of the CollectionViewSource property (that is perfectly bindable). Now during VM initialization I need to setup everything.
I create the ObservableCollection, the new CollectionViewSource and add the collection to the source, then bound the event ApplyFilter wrote this way.
The function ApplyFilter filters object based on another property of the VM called StatusFilter, of the same type of the enum property used in the bound object. In the setter part of the StatusFilter property simply call a function that refresh the view. Now I can simply add a combo in the View, bind the SelecteValue property to the StatusFilter VM property and without any other change Iâ€™ve added filtering capabilities to the View.
The cool part is that Iâ€™m able to write unit test that verify filtering capabilities.
Iâ€™ve added two SingleAnalysisLink to the VM, then change the status of only one of them to Match, set a filter to show only item with status == Match and assert that the count of items of the view is Equal To 1.