wpf - 如何将自定义排序规则应用于 WPF DataGrid?

标签 wpf xaml sorting mvvm wpftoolkit

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

我写了一个 IComparer<T>这确保空白总是向下排序,但我不知道如何将它应用到我的 DataGrid 的列中。 .注意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 友好的解决方案。

最佳答案

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

附加到排序事件

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

关于wpf - 如何将自定义排序规则应用于 WPF DataGrid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2129601/

相关文章:

c# - 如何将 Wpf 项目迁移到新的 VS2017 格式

c# - WPF 使用 DataBinding 根据其值设置标签背景

java - 对字符串列表进行排序

c# - 修复了 XAML 中的定位

c# - Visual Studio 2010 中的 MVVM?

wpf - 数据触发器绑定(bind)未按预期工作

algorithm - 惰性求值和时间复杂度

java比较逗号分隔的字符串

wpf - 将其 LayoutTransform 设置为 TranslateTransform 或 MatrixTransform 时,Canvas 子项的翻译不起作用

c# - Windows Phone 8.1 超链接按钮和保存状态