Reputation: 46460
My datagrid is setup like this:
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();
}
}
}
Upvotes: 1
Views: 2871
Reputation: 41
My method is work for me. Just try this code.
if (dgEvents.ItemsSource == null)
dgEvents.ItemsSource = events.Entries;
CollectionViewSource.GetDefaultView(dgEvents.ItemsSource).Refresh();
dgEvents.Items.SortDescriptions.Clear();
dgEvents.Items.SortDescriptions.Add(new SortDescription(dgEvents.Columns[0].SortMemberPath, ListSortDirection.Descending));
foreach (var col in dgEvents.Columns)
{
col.SortDirection = null;
}
dgEvents.Columns[0].SortDirection = ListSortDirection.Descending;
dgEvents.Items.Refresh();
Upvotes: 0
Reputation: 46460
My solution was to manually track the sorted columns in the derived DataGrid class, which is working well.
https://github.com/ronnieoverby/RonnieOverbyGrabBag/blob/master/DataGrid.cs
Upvotes: 1