Making a Better ObservableCollection Part 4 – Enhancing DataGrid Sorting

Welcome to the last part our series Making a Better ObservableCollection. If you missed Making a Better ObservableCollection Part 3 – Sorting you can get to it here. To wrap up using our extended ObservableCollection and Sorting, we are going to implement enhanced datagrid sorting by overriding the default sorting behavior with our new Sorting method.

Q: Why?
A: A fair question. It’s been found through multiple speed tests that using the default sort behavior of a DataGrid is actual rather slow on large data sets. Overriding this behavior with the method shown in Part 3 has been proven to greatly increase performance. More about that can be found in the original article which I based my research on here.

First, we need to set our UpdateSort method that will be called any time we sort our DataGrid with our extended ObservableCollection MyCollection:

/// <summary>
/// Updates the observable collection to the current sort context.
/// </summary>
public void UpdateSort(DataGridColumn sortColumn, ListSortDirection sortDirection)
    // As sort column needs to be present to sort.
    if (sortColumn == null) return;

    // Maintain sort direction
    sortColumn.SortDirection = sortDirection;

    // Sort member
    var sortMemberPath = sortColumn.SortMemberPath;

    // Sort
    this.MyCollection.Sort(sortMemberPath, sortDirection);

All we are doing here is setting the sort column and the sort direction. These are required for the Sort method to be executed.

Now, all we need to do is set the Sorted event of our DataGrid to ignore it’s own behavior and to use our new UpdateSort method instead:

/// <summary>
/// Handles sorting event for Data grid.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Windows.Controls.DataGridSortingEventArgs"/> 
/// instance containing the event data.</param>
public void DataGridSorting(object sender, DataGridSortingEventArgs e)
    // Prevent the built-in sort from sorting
    e.Handled = true;

    // Get current sort column
    var sortColumn = e.Column;
    var sortDirection =
        (SortColumn.SortDirection != ListSortDirection.Ascending) ?
        ListSortDirection.Ascending : ListSortDirection.Descending;

    // Sort
    // Call Sorted event on complete
    UpdateSort(sortColumn, sortDirection);

The key here is setting e.Handled = true to tell the Sorting event “It’s taken care of”, so that we can do whatever we want in it’s stead.

And just like that, we have overridden the default sorting behavior of our DataGrid to use our custom method to handle sorting an extended ObservableCollection.

I hope you enjoyed this 4-part series on extending an ObservableCollection.


No comments yet.

Leave a Reply