I am struggling with finding an adequate solution to impletmenting Sorting and Paging for a WPF DataGrid that conforms to the MVVM P&P.
The following example illustrates an effective way to implement paging which follows MVVM practices, but the custom implementation of sorting (which is required once you implement paging) does not follow MVVM:
I currently have a DataGrid bound to a CollectionViewSource (defined in XAML with GroupDescriptions and SortDescritptions) bound to an ObservableCollection in my ViewModel. As soon as you implement Paging by limiting the number of items your DataGrid gets per page, it breaks the sorting defined in the CollectionViewSource because it is only sorting the subset of items. What is the best approach under MVVM to implement Paging and Sorting?
Thanks,
Aaron
The other day I wrote a
PagingControllerclass to help with paging, so here you go:You will have to clean up the sources a bit because the make some use of MS Code Contracts, they reference some (really basic) utility stuff from Prism, etc.
Usage sample (codebehind –
ViewModel.cs):Usage sample (XAML –
View.xaml):Short explanation:
As you see, the ViewModel doesn’t really do much. It keeps a collection of items representing the current page, and exposes a
CollectionView(for data binding) and aPagingControllerto the View. Then all it does is update the data items in the collection (and consequently in theCollectionView) every time thePagingControllerindicates that something has changed. Of course this means that you need a method that, given a starting index, a page size, and aSortDescription[]returns the slice of data described by these parameters. This is part of your business logic, and I haven’t included code for that here.On the XAML side all the work is done by binding to the
PagingController. I have exposed the full functionality here (buttons bound to First/Prev/Next/Last commands, direct binding of aTextBoxtoCurrentPage, and binding of aScrollBartoCurrentPage). Typically you will not use all of this at the same time.