我自己刚遇到这个问题,我的解决方案是拦截 Sorting 事件,让 ICollectionView 在 ViewModel 中进行排序,而不是依赖 DataGrid 来处理它。
XAML:
<DataGrid ItemsSource="{Binding StatusItemsGrouped}" Sorting="OnSorting_"/>
XAML.CS:
private void OnSorting_(object sender, DataGridSortingEventArgs e)
{
var viewModel = DataContext as ViewModel;
e.Handled = true; // prevent DataGrid from sorting
viewModel.SortItemSource(e.Column); // perform sorting
e.Column.SortDirection = viewModel.SortDirection; // set sort direction icon on column header
}
视图模型:
public class ViewModel
{
public ListCollectionView StatusItemsGrouped { get; set; }
public ListSortDirection SortDirection { get; set; }
public string SortColumn { get; set; }
public void SortItemSource(string columnName)
{
if (String.Compare(SortColumn, columnName, true) == 0)
SortDirection = ListSortDirection.Ascending;
else
SortDirection = ListSortDirection.Descending;
SortColumn = columnName;
using(StatusItemsGrouped.DeferRefresh()) {
StatusItemsGrouped.GroupDescriptions.Clear();
StatusItemsGrouped.SortDescriptions.Clear();
StatusItemsGrouped.SortDescriptions.Add(new SortDescription(SortColumn, SortDirection));
StatusItemsGrouped.GroupDescriptions.Add(new PropertyGroupDescription("GenericStatus"));
}
StatusItemsGrouped.Refresh();
}
}