Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVP/MVVM - Filtering of lists, who has responsibility?

I'm implementing a wpf application which display a list of items, and provides the functionality to filter this list by typing in a textbox (quite trivial use case i think).

We're using a MVVM structure.

My question is, whose responsibility is it to filter the list? The view or the viewmodel? Should I implement an "OnTextChanged" event in the xaml.cs, or should I use a property in the ViewModel and use the PropertyChanged to filter the list.
Follow-up question is, should I use a BindingList/ObservableCollection in the ViewModel, or use a ICollectionView to bind the ItemsControl to?

I tried both methods, and they both work. Giving the ViewModel the responsibility keeps the code behind from the View empty, but on the other hand I'm not completely convinced that it is the ViewModels responsibility to apply filtering (eg: different views might require different filtering)

Any thoughts?

thanks, Roel

EDIT:

what bothers me about putting it in the ViewModel is that (in my current implementation) there is a reference the System.Windows.Data. This is a reference I'd rather not have in the ViewModel because it is clearly something View related. Or am I missing something? relevant code:

ICollectionView customerView = CollectionViewSource.GetDefaultView(customers);
like image 646
RoelF Avatar asked Oct 16 '09 08:10

RoelF


2 Answers

ViewModel, without any doubt. Avoiding code-behind is the ultimate goal of the pattern - in fact, ViewModel itself is the code behind view.

eg: different views might require different filtering

Different views should have different ViewModels. ViewModel is basically a (somewhat more) object-oriented approach to code-behind files.

Regarding CollectionView: you can define CollectionViewSource in the view XAML, and then bind its sorting and filtering properties to ViewModel. That should keep control in ViewModel and CollectionView in view, but I believe it's over-engineering.

like image 104
ima Avatar answered Sep 30 '22 16:09

ima


You can check out this article on my blog where I use the MVVM methodology to filter a collection of items. I think this is definitively the responsibility of the VM class.

like image 25
japf Avatar answered Sep 30 '22 18:09

japf