My datagrid is setup like this:
- ItemsSource bound to ObservableCollection
- Handling Sorting event
- e.Handled = true;
- Clear observable collection
- Query database with sorting logic
- Foreach result add to observable collection
This works great but I want to enable multiple column sorting. It's my understanding that holding shift while clicking column headings is the way the end user does this. But in the sorting event, I don't know how to get a hold of the sort descriptions.
Here's my code for single column server side sorting, which works fine:
public class DataGrid : System.Windows.Controls.DataGrid
{
public event EventHandler<SortExpressionConstructedEventArgs> SortExpressionConstructed;
public void OnSortExpressionConstructed(SortExpressionConstructedEventArgs e)
{
EventHandler<SortExpressionConstructedEventArgs> handler = SortExpressionConstructed;
if (handler != null) handler(this, e);
}
public DataGrid()
{
Sorting += DataGridSorting;
}
void DataGridSorting(object sender, System.Windows.Controls.DataGridSortingEventArgs e)
{
e.Handled = true;
e.Column.SortDirection = e.Column.SortDirection != ListSortDirection.Ascending
? ListSortDirection.Ascending
: ListSortDirection.Descending;
var sd = new SortDescription(e.Column.SortMemberPath, e.Column.SortDirection.Value);
OnSortExpressionConstructed(new SortExpressionConstructedEventArgs(sd));
}
}
public class SortExpressionConstructedEventArgs : EventArgs
{
public SortExpressionConstructedEventArgs(SortDescription sortDescription)
{
SortDescription = sortDescription;
}
public SortDescription SortDescription { get; private set; }
// event handler can use this to sort the query
public IOrderedQueryable<T> Order<T>(IQueryable<T> queryable)
{
switch (SortDescription.Direction)
{
case ListSortDirection.Ascending:
return enumerable.OrderBy(SortDescription.PropertyName);
case ListSortDirection.Descending:
return enumerable.OrderByDescending(SortDescription.PropertyName);
default:
throw new ArgumentOutOfRangeException();
}
}
}