Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-sort WPF DataGrid after bounded Data has changed

I am looking for a way to re-sort my DataGrid when the underlying data has changed.

(The setting is quite standard: The DataGrid's ItemSource property is bound to an ObservableCollection; The columns are DataGridTextColumns; The data inside the DataGrid reacts correctly on changes inside the ObservableCollection; Sorting works fine when clicked with the mouse)

Any ideas ?

like image 855
marc wellman Avatar asked Jul 16 '12 13:07

marc wellman


1 Answers

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<T> and wrap the CollectionViewSource around the ObservableCollection:

// Gets or sets the CollectionViewSource public CollectionViewSource ViewSource { get; set; }  // Gets or sets the ObservableCollection public ObservableCollection<T> Collection { get; set; }  // Instantiates the objets. public ViewModel () {      this.Collection = new ObservableCollection<T>();     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:

<DataGrid ItemsSource="{Binding ViewSource.View}" /> 

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.

like image 179
marc wellman Avatar answered Oct 07 '22 00:10

marc wellman