user1154096
user1154096

Reputation:

Persist sorting from DataGrid to ItemsSource collection

I have a DataGrid and I'm trying to do the Sort thing the most straightforward way: by clicking on the header of each column.

This is working great on the View (in the MVVM context), but I want to sort the underlying ViewModel collection (ObservableCollection) too. Any suggestions on how to implement the source collection?

Upvotes: 1

Views: 1228

Answers (1)

Barracoder
Barracoder

Reputation: 3764

Bind the grid to a ListCollectionView, initialised with the ObservableCollection. The grid will use your pre-created ICollectionView instead of creating it's own ICollectionView based on your ObservableCollection<T> (which is the default behaviour), and apply any sorting functionality/predicates to your instance.

As an added benefit, sorting/filtering that ListCollectionView will be reflected in your grid whenever you call MyListCollectionView.Refresh() from your ViewModel.

Once you've done this, iterating through the Items collection of your ListCollectionView will accurately reflect the current filter/sort state of your grid.

Upvotes: 1

Related Questions