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

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

问题描述

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

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天全站免登陆