我的数据网格设置如下:
这很好但我想启用多列排序。我的理解是,在点击列标题时按住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();
}
}
}
答案 0 :(得分:1)
我的解决方案是手动跟踪派生的DataGrid类中的已排序列,该列运行良好。
https://github.com/ronnieoverby/RonnieOverbyGrabBag/blob/master/DataGrid.cs
答案 1 :(得分:0)
我的方法对我有用。试试这个代码。对不起俄罗斯
// Если таблица пустая, то привязываем ее к журналу
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();