views:

25

answers:

1

Hi All,

I am using an MVVM approach.

I have a ViewModel and View called AllSomethingViewModel and AllSomethingView. The View Model contains a list of SomethingViewModels and a SelectedViewModel. The View contains a usercontol bound to the AllSomethingViewModel's SelectedVM property and a listbox control that lets me select a VM. Basically when I pick a new VM the usercontrol's DataContext changes and so the view associated with SomethingViewModel updates with new information.

SomethingViewModel contains a list of objects called ObservableCollection(DataPoints) data.

I have a DataGrid bound to data and columns defined that are bound to data's members. This works fine. I can change views and this datagrid updates and everything is nice.

The issue I am running into is that I would like whatever sorting is applyed to the datagrid to persist when the datacontext changes.

On the View associated with SomethingViewModel, I can subscribe to DataContextChanged event but I'm not sure what To do from there to get the sorting to apply.

For Example. I have 2 SomethingViewModels. So in my list there are 2 options. When i pick the first one I get my datagrid with my data. In the datagrid I decide to sort by DateCreated Ascending order. Then I go to my second VM, the datacontext changes so the data in the grid is updated but it is no longer sorted!

A: 

If your sorting is done by the DataGrid then it is stored in the ICollectionView that the DataGrid uses to display its data.

ICollectionView view = CollectionViewSource.GetDefaultView(myDataGrid.ItemsSource);
// Sorting is found in view.SortDescriptions

There's an example of setting your sorting in code here. Hope that's enough to get you going in the right direction

Rachel