【问题标题】:How can I apply a custom sort rule to a WPF DataGrid?如何将自定义排序规则应用于 WPF DataGrid?
【发布时间】:2010-01-25 00:51:09
【问题描述】:

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

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

【问题讨论】:

标签: wpf xaml sorting mvvm wpftoolkit


【解决方案1】:

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

附加到排序事件

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

【讨论】:

  • 请注意,根据您的 DataGrid 绑定的集合类型,您可能必须将 GetDefaultView 的结果转换为 A Different Type
【解决方案2】:

我有一个针对这个问题的 MVVM 解决方案,它利用了附加行为。如果您更喜欢使用代码隐藏,@Aran 的解决方案也可以解决问题。

https://stackoverflow.com/a/18218963/2115261

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 2015-02-09
    • 2011-07-31
    • 2013-06-16
    • 2011-12-26
    • 2016-09-23
    • 1970-01-01
    • 2021-04-02
    • 2012-05-01
    相关资源
    最近更新 更多