[英]Datagrid Multiple Column Sorting
我的數據網格設置如下:
這很好用,但我想啟用多列排序。 我的理解是,在單擊列標題時按住 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();
}
}
}
我的解決方案是手動跟蹤派生的 DataGrid 類中的排序列,這運行良好。
https://github.com/ronnieoverby/RonnieOverbyGrabBag/blob/master/DataGrid.cs
我的方法對我有用。 試試這個代碼。
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.