WPF使用重置对DataGrid进行排序

时间:2019-01-15 07:33:40

标签: c# wpf sorting

我对DataGrid有自定义排序

if (sortPropertyName == "Ip")
{   
     IComparer comparer = null;                    
     e.Handled = true;
     ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;         
     e.Column.SortDirection = direction;         
     ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);                     
     comparer = new SortIPAddress(direction);                   
     lcv.CustomSort = comparer;
}

效果很好。我为其他列设置了方法重置排序

if (e.Column.SortDirection.HasValue && e.Column.SortDirection.Value == ListSortDirection.Descending)
{                    
    int index = Helpers.FindSortDescription(dataGrid.Items.SortDescriptions, sortPropertyName);
    if (index != -1)
     {
         e.Column.SortDirection = null;
         // remove the sort description
         dataGrid.Items.SortDescriptions.RemoveAt(index);
         dataGrid.Items.Refresh();

         if ((Keyboard.Modifiers & ModifierKeys.Shift) != ModifierKeys.Shift)
         {
           // clear any other sort descriptions for the multisorting case
           dataGrid.Items.SortDescriptions.Clear();
           dataGrid.Items.Refresh();
         }

         // stop the default sort
         e.Handled = true;
     }
}

如何像在IP列中那样进行重置?

我做到了:

if (e.Column.SortDirection.HasValue && e.Column.SortDirection.Value == ListSortDirection.Descending)
{
  e.Column.SortDirection = null;
}
else
{
  ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;                        
  e.Column.SortDirection = direction;
  comparer = new SortIPAddress(direction);
}                    
ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);                   
lcv.CustomSort = comparer;

排序Ip现在重置。但是用shift进行双重排序是不正确的。如何解决?

1 个答案:

答案 0 :(得分:0)

您可以通过将SortDirection属性设置为null来清除列的排序:

e.Column.SortDirection = null;

如果要删除自定义排序,可以将CustomSort属性设置为null

ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg.ItemsSource);
lcv.CustomSort = null;