如何在WPF DataGrid中应用自定义排序规则?

29

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

我编写了一个IComparer<T>来确保空白总是向下排序,但我无法将其应用到我的DataGrid的列上。请注意,使用LINQ的OrderBy()方法进行初始排序非常好用。问题在于由用户执行的所有后续排序都将空白单元格排序到顶部。

比较器代码

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 友好的解决方案。


你可以采用这种方法,非常灵活且易于使用。 - lezhkin11
2个回答

33

这是我的做法:我从grid派生出来,以便将所有内容保留在类内部,因此我内部附加到事件处理程序。

附加到排序事件。

dataGrid.Sorting += new DataGridSortingEventHandler(SortHandler);

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

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;
}

3
请注意,根据您的DataGrid绑定的集合类型,您可能需要将GetDefaultView的结果转换为[A Different Type](http://msdn.microsoft.com/en-us/library/ms752347.aspx#how_to_create_a_view)。 - xr280xr

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接