Sorting a specific DataGridColumn in a DataGrid

Sep 13, 2010 at 7:42 AM

Hi!

I have a WPF DataGrid that has several DataGridColumns, one of these columns is bound to a Property that is an abstract class. Like this: 

 

 public class Cat
  {
    public AbstractCatType Type { get; set; }
  }

  public class AbstractCatTypeToStringConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      if (value is NiceCatType)
      {
        return "Nice"; 
      }

      if (value is BadCatType)
      {
        return "Bad";
      }

      return "unknown";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new System.NotImplementedException();
    }
  }
 

When i click the column header to sort this column I get (not very suprising) an exception System.InvalidOperationException was unhandled Message="Failed to compare two elements in the array."

I would like the column to get sorted on the string values it contains (Bad, Nice) but how can I do that? I would prefer to specify a Comparer class for that column or if I could make it forget about the property that it is bound to and sort the strings written in the column. I would prefer not to have to create specific comparers for all of my columns and I have no other SortMemberPath to redirect the sorting to.  Does anyone know how to do that or is there I way I can do it? Do I have to bind it to another property that it can sort on? 

 

Regards, Lina