MVVM what part of pattern responsible for grouping of datagrid
I've been tinkering around with the MVVM pattern and now I'm trying to implement a little application based on it.
This application has a data开发者_StackOverflowgrid in which, surprisingly enough, some data is presented. Now I'm trying to add some grouping ability to it. I know how to write this in code (C# and XAML), but I'm wondering in what layer I should put the responsible code.
One part of me tells me it should be in the view, because it's code especially for that specific view. It's not generic and serves one purpos: to group the data.
On the other hand I think I should handle it in the ViewModel using a command. It feels, though, as if I'm contaminating my ViewModel with View specific logic.
Any ligt that can be shed on this?
In most of my MVVM apps I try to divide responsibilities like this:
- The view should just perform a simple translation of viewmodel data to pixels. Usually this results in mostly XAML and very little code behind.
- The viewmodel should perform view-specific logic like grouping etc. I often even have multiple viewmodels per view. You can have a main viewmodel that exposes a list of sub-viewmodels per group to your view for example to implement grouping.
- If you have any logic that applies to more than one viewmodel it's probably domain logic and should go into the domain model.
So I think grouping should go in the viewmodel.
There is no one answer to this. It really depends on your scenario:
1) Does the user have any influence on the matter? If they do not, and it's a fixed grouping, I'd publish a property with IGrouping and use the dataservice or LINQ to do it before it enters the view.
It is typically less performant if you do grouping in the view, but it's not a clear-cut choice. If the user can select a lot of different groupings, this might be a penalty worth paying for the added usability..
if the user has some influence on the grouping I'd bind to an ICollectionView exposed by the ViewModel. The view supports grouping, filtering, sorting and currency and the ICollectionView interface is from System.ComponentModel so you wouldn't have to add a "gui" reference to your ViewModel project. Also the WPF DataGrid supports the ICollectionView interface.
If the user has no influence on the grouping (the groups are fixed) I'd just "pre"-group the data in the model. HTH.
精彩评论