如何将自定义排序规则应用于 WPF DataGrid? [英] How can I apply a custom sort rule to a WPF DataGrid?

查看:45
本文介绍了如何将自定义排序规则应用于 WPF DataGrid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在我的 DataGrid 中进行列排序时,我希望将所有空单元格或空单元格排序到底部,而不是顶部.

When the user does a column sort in my DataGrid, I want all null or empty cells to be sorted to the bottom, rather than the top.

我写了一个 IComparer<T> 来确保空格总是向下排序,但我不知道如何将它应用到我的 DataGrid 的列.请注意,我正在使用 LINQ OrderBy() 方法对 DataGrid 进行 initial 排序,效果很好.问题是用户执行的所有后续排序都将空白排序到顶部.

I wrote an IComparer<T> that makes sure blanks are always sorted downward, but I can't figure out how to apply it to the columns of my DataGrid. Note that the initial sort of the DataGrid, which I'm doing with the LINQ OrderBy() method, works great. The problem is that all subsequent sorts performed by the user sort the blanks to the top.

比较代码

public class BlankLastStringComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        if (string.IsNullOrEmpty(x) && !string.IsNullOrEmpty(y))
            return 1;
        else if (!string.IsNullOrEmpty(x) && string.IsNullOrEmpty(y))
            return -1;
        else
            return string.Compare(x, y);
    }
}

问题

如何让 DataGridColumn 使用我的比较器?或者,如果这是不可能的,您能否提供解决方法?如果可能,我希望有一个 MVVM 友好的解决方案.

How do I get the DataGridColumn to use my comparer? Or if this is not possible, can you offer a workaround? I'm hoping for an MVVM friendly solution if possible.

推荐答案

我是这样做的:我确实从网格派生以将所有这些保存在类中,因此我在内部附加到事件处理程序

this is how i do it : I do derive from the grid to keep all of this inside the class, so i attach to event handlers internally

附加到排序事件

dataGrid.Sorting += new DataGridSortingEventHandler(SortHandler);

实现方法(我在派生类中这样做)

implement the method (i do this in a derived class)

void SortHandler(object sender, DataGridSortingEventArgs e)
{
    DataGridColumn column = e.Column;

    IComparer comparer = null;

    //i do some custom checking based on column to get the right comparer
    //i have different comparers for different columns. I also handle the sort direction
    //in my comparer

    // prevent the built-in sort from sorting
    e.Handled = true;

    ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;

    //set the sort order on the column
    column.SortDirection = direction;

    //use a ListCollectionView to do the sort.
    ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(this.ItemsSource);

    //this is my custom sorter it just derives from IComparer and has a few properties
    //you could just apply the comparer but i needed to do a few extra bits and pieces
    comparer = new ResultSort(direction);

    //apply the sort
    lcv.CustomSort = comparer;
}

这篇关于如何将自定义排序规则应用于 WPF DataGrid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆