dev*_*xer 25 sorting wpf xaml mvvm wpftoolkit
当用户在我的列中进行排序时DataGrid
,我希望将所有null或空单元格排序到底部,而不是顶部.
我写了一个IComparer<T>
确保空白总是向下排序,但我无法弄清楚如何将它应用到我的列DataGrid
.请注意,我使用LINQ 方法进行的初始排序DataGrid
很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);
}
}
Run Code Online (Sandbox Code Playgroud)
问题
如何DataGridColumn
使用我的比较器?或者,如果这不可能,您能提供解决方法吗?如果可能的话,我希望有一个MVVM友好的解决方案.
Ara*_*and 29
这是我如何做到的:我从网格派生出来将所有这些保留在类中,所以我在内部附加到事件处理程序
附加到排序事件
dataGrid.Sorting += new DataGridSortingEventHandler(SortHandler);
Run Code Online (Sandbox Code Playgroud)
实现方法(我在派生类中执行此操作)
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;
}
Run Code Online (Sandbox Code Playgroud)
对于这个问题,我有一个 MVVM 解决方案,它利用了附加的行为。如果您更喜欢使用代码隐藏,@Aran 的解决方案也可以解决问题。
归档时间: |
|
查看次数: |
29466 次 |
最近记录: |