Weird behavior with DataModelSortComparer

Grids for WPF Forum

Posted 6 years ago by Antoine Picard
Version: 18.1.0673
Platform: .NET 4.7
Environment: Windows 10 (64-bit)
Avatar

Hi,

I wanted to do something similar to the Sorting example in your sample so I created a class inheriting from DataModelSortComparer. Then I overriden the Compare function like this :

public override int Compare(IDataModel x, IDataModel y)
{
 // Sort the "Basic" category before anything else and "To Test" after anything else
 if (x is ICategoryModel xCategoryModel && y is ICategoryModel yCategoryModel)
 {
  switch (xCategoryModel.Name)
  {
   case "Basic":
    return 1;
   case "To Test":
    return -1;
   default:
    return 0;
  }
 }
}

 As I indicated in the comment, I want to have this kind of order for my 3 categories:
- Basic
- MyCat
- To Test

But what I have is :
- MyCat
- To Test
- Basic

Do you know why ? I can't find any logic about it.

AP

Edit : I tried with four categories and it's even weirder
- To Test
- Basic
- MyCat
- FourthOne

[Modified 6 years ago]

Comments (3)

Answer - Posted 6 years ago by Antoine Picard
Avatar

Ok, found the problem myself, I also hae to return values depending of yCategoryModel.
So here's my final code :

public override int Compare(IDataModel x, IDataModel y)
{
 // Sort the "Basic" category before anything else and "To Test" after anything else
 if (x is ICategoryModel xCategoryModel && y is ICategoryModel yCategoryModel)
 {
  switch (xCategoryModel.Name)
  {
   case "Basic":
    return -1;
   case "To Test":
    return 1;
   default:
    switch (yCategoryModel.Name)
    {
     case "Basic":
      return 1;
     case "To Test":
      return -1;
     default:
      return 0;
    }
  }
 }
}

[Modified 6 years ago]

Posted 6 years ago by Actipro Software Support - Cleveland, OH, USA
Avatar

Hi Antoine,

When you make a sort comparer, you need to have it handle each item.  You are returning 0 (meaning equal) for a number of things so that will sort them in random orders.  Instead of returning zero for things you don't care about, return base.Compare(x, y).  That will keep order properlly and will prevent the randomness you see.

Also note that WPF sort comparers will sometimes pass things in x or y.  You can't really predict, so you need to handle both x and y scenarios.  Your code was originally only handling x but as you saw later you need to do both.  And also I think you originally had it backwards in that -1 should be for first, and 1 is for last and corrected that in the latter code.


Actipro Software Support

Posted 6 years ago by Antoine Picard
Avatar

Hi !

thanks for your feedback and your explanations ! I'll change this 0 stuff :)

And yes it was more intuitive for me to have the 1 at highest place and -1 lowest :) but still ok !

The latest build of this product (v24.1.3) was released 2 months ago, which was after the last post in this thread.

Add Comment

Please log in to a validated account to post comments.