当用户在我的 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/