Programmatic sorting

Sep 18, 2008 at 8:49 PM

I built a sort dialog to make it a little easier for my users to do a multi column sorts on the datagrid.  My datagrid is bound to a datatable.  To sort the datagrid, I just sort the bound datatable.  However, if I click on a column header to sort one column, my custom sorting stops working. 

Is there a better way to do this?  Is there a way to sort the datagrid instead of the datatable programmatically?  If so, does anyone have some sample code that shows how to sort a datagrid programmatically?

Sep 18, 2008 at 11:13 PM
You should avoid touching the actual data whenever possible.  Fortunately, the controls you see are not actually bound to the data and are instead bound to an intermediate representation of type ICollectionView.  ICollectionView is designed to handle sorting, filtering and grouping (excellent explanation here: http://www.beacosta.com/blog/?cat=13).  For sorting, you can use the SortDescriptions collection, which evaluates each SortDescription in the order it appears each time the ICollectionView is refreshed.  Lets say you have a collection of Users that have properties FirstName and LastName.  The code below shows how you can sort these objects without touching the actual data. 

    ICollectionView view = CollectionViewSource.GetDefaultView(usersDataGrid.ItemsSource);
    view.SortDescriptions.Clear();
    view.SortDescriptions.Add(new SortDescription("FirstName", ListSortDirection.Descending));
    view.SortDescriptions.Add(new SortDescription("LastName", ListSortDirection.Descending));
    view.Refresh();

I assume that the DataGrid uses this same methodology internally when you click a column header.  Therefore, if you wish to have additional controls to handle sorting, you should clear out the SortDescriptions collection before adding your own to eliminate conflicts or unexpected behavior.
Coordinator
Sep 19, 2008 at 1:15 AM
That is correct in that the DataGrid internally just creates a sort description when you click on the column header.  It also clears any other sort descriptions when you click on the column header.  Here are a couple posts with samples where sorting is customized.  Hopefully they can help.  Also, if you are interested in understanding the implementation details just look in the region named "Auto Sort" in DataGrid.cs in the CTP.

http://blogs.msdn.com/jgoldb/archive/2008/08/26/improving-microsoft-datagrid-ctp-sorting-performance.aspx

http://blogs.msdn.com/vinsibal/archive/2008/08/29/wpf-datagrid-tri-state-sorting-sample.aspx
Sep 23, 2008 at 9:28 PM
I just had a chance to look at this today.  It works great.  Thanks for your help!