简体   繁体   中英

WPF sorting DataGrid with reset

I have custom sort for my 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;
}

It works well. And I have method reset sort for other column

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

How Can I do reset like in column Ip?

I did:

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;

Sorting Ip resets now. But double sorting with shift is incorrect. How to fix?

You can clear the sorting of a column by setting the SortDirection property to null :

e.Column.SortDirection = null;

If you want to remove your custom sorting, you could set the CustomSort property to null :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM