WPF - using custom mapping when sorting across multiple columns

I have a ListView (GridView) that I want to sort by 2 columns, so if 2+ items have the same value in column 1, it is sorted by column 2. Pretty easy. But when sorting AZ, empty lines appear at the top. I would like to move them to the bottom. I made a comparator (IComparer) that takes care of this, but I'm not sure how to use it.

Here is the code I tried:

 Dim view As ListCollectionView = CollectionViewSource.GetDefaultView(myCollection)
 Using view.DeferRefresh
    view.SortDescriptions.Clear()
    view.SortDescriptions.Add(New SortDescription(sortHeader.Header, direction))
    view.SortDescriptions.Add(New SortDescription(otherColumn, direction))
    view.CustomSort = New MyComparer()
 End Using

The problem is that my mapper is assigned the type of my class instead of the property / column sort value. So if the class is Foo and I sort Foo.Bar, I get the whole Foo class, not just the Bar value (in fact, this should all be worried, since this is what it sorts).

How does my companion find out which property to compare? Maybe I'm doing something wrong here because it makes no sense. I was expecting to get a String (property type) for x and y ...

Does anyone know how to do this?

+5
source share
1 answer

An IComparerentire object will be provided in your implementation , you need to figure out which column is clicked, perhaps by doing something like this:

this.AddHandler(GridViewColumnHeader.ClickEvent, 
                new RoutedEventHandler(Column_Sort));

and then load it into MyComparer, perhaps by modifying your constructor to go along the property path.

In Column_Sortyou can get the property path something like this (I'm a little rusty on vb, but C # would do this:

void Column_Sort(object sender, RoutedEventArgs e)
{
  var memberBinding= ((GridViewColumnHeader)e.OriginalSource).Column.DisplayMemberBinding;
  var path = ((Binding)memberBinding).Path.Path;
}

and then enter this into the sorting logic.

Dim view As ListCollectionView = CollectionViewSource.GetDefaultView(myCollection)
 Using view.DeferRefresh
    view.SortDescriptions.Clear()
    view.SortDescriptions.Add(New SortDescription(sortHeader.Header, direction))
    view.SortDescriptions.Add(New SortDescription(otherColumn, direction))
    view.CustomSort = New MyComparer(PropertyPath)
 End Using

EDIT: IComparer , google , , ASC/DESC :

User.LastName DESC, User.FirstName DESC

, , Ctrl. , ListView GridViewColumnHeader KeyDown, , , IComparer .

+6

All Articles