我的数据网格是这样设置的:
- ItemsSource 绑定到 ObservableCollection
- 处理排序事件
- e.Handled = true;
- 清除 observable 集合
- 使用排序逻辑查询数据库
- Foreach 结果添加到可观察集合
这很好用,但我想启用多列排序。据我了解,在单击列标题时按住 shift 是最终用户执行此操作的方式。但是在排序事件中,我不知道如何获取排序描述。
这是我的单列服务器端排序代码,效果很好:
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();
}
}
}