I am looking for a way to re-sort my DataGrid when the underlying data has changed.
(The setting is quite standard: Th
It took me the whole afternoon but I finally found a solution that is surprisingly simple, short and efficient:
To control the behaviors of the UI control in question (here a DataGrid) one might simply use a CollectionViewSource. It acts as a kind of representative for the UI control inside your ViewModel without completely breaking the MVMM pattern.
In the ViewModel declare both a CollectionViewSource and an ordinary ObservableCollection and wrap the CollectionViewSource around the ObservableCollection:
// Gets or sets the CollectionViewSource
public CollectionViewSource ViewSource { get; set; }
// Gets or sets the ObservableCollection
public ObservableCollection Collection { get; set; }
// Instantiates the objets.
public ViewModel () {
this.Collection = new ObservableCollection();
this.ViewSource = new CollectionViewSource();
ViewSource.Source = this.Collection;
}
Then in the View part of the application you have nothing else to do as to bind the ItemsSource of the CollectionControl to the View property of the CollectionViewSource instead of directly to the ObservableCollection:
From this point on you can use the CollectionViewSource object in your ViewModel to directly manipulate the UI control in the View.
Sorting for example - as has been my primary problem - would look like this:
// Specify a sorting criteria for a particular column
ViewSource.SortDescriptions.Add(new SortDescription ("columnName", ListSortDirection.Ascending));
// Let the UI control refresh in order for changes to take place.
ViewSource.View.Refresh();
You see, very very simple and intuitive. Hope that this helps other people like it helped me.