繁体   English   中英

Datagrid 多列排序

[英]Datagrid Multiple Column Sorting

我的数据网格设置如下:

  • ItemsSource 绑定到 ObservableCollection
  • 处理排序事件
    • e.handled = true;
    • 清除可观察集合
    • 使用排序逻辑查询数据库
    • 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();
        }
    }
}

我的解决方案是手动跟踪派生的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM