1

I have an ObservableCollection<string>:

public ObservableCollection<string> Collection { get; set; } = new ObservableCollection<string>
{
    "AA",
    "BB",
    "CC",
    "C",
    "A",
    "C",
    "BBB",
    "AAA",
    "CCC"
};

A ListBox in the Window binds to this Collection. In the Window Loaded event, I am assigning sorting and grouping logic to the underlying ICollectionView of the Collection.

private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
    ICollectionView defaultView = CollectionViewSource.GetDefaultView(this.Collection);
    defaultView.GroupDescriptions.Add(new PropertyGroupDescription(null, new TestGroupConverter()));

    defaultView.SortDescriptions.Add(new SortDescription("", ListSortDirection.Ascending));
    defaultView.SortDescriptions.Add(new SortDescription("", ListSortDirection.Descending));
}

TestGroupConverter returns the length of the string in its convert method.

So here's the result:

enter image description here

I expected the groups to be sorted in ascending order and items within it to be sorted by descending order. But it appears that the SortDescription for items within the group is not used — It's not sorted in Descending order.

I'm not sure what I am doing wrong.

Ilan
  • 2,762
  • 1
  • 13
  • 24
wingerse
  • 3,670
  • 1
  • 29
  • 61
  • Get the first letter of string: `collection.OrderBy(x>x.Substring(0,1))` – Maciej Los Apr 16 '16 at 18:22
  • @MaciejLos, I didn't understand. SortDescription uses the Default Comparer for strings. – wingerse Apr 16 '16 at 18:42
  • @EmperorAiman did you try changing first `SortDescription` to `new SortDescription("Length", ListSortDirection.Ascending)` so primary sort is by items length? – dkozl Apr 16 '16 at 20:06
  • @dkozl, ah. Yes. That fixed the problem. I thought the first sortdescription uses the `CollectionViewGroups.Name` for it's sorting. My bad. So sorting is independent of grouping. Thanks. You can make this into an answer if you want. I will accept it. – wingerse Apr 16 '16 at 20:27

1 Answers1

3

All sort descriptions apply to items even when you use grouping and you have two sort descriptions with the same property. Unfortunately you cannot sort by converted value but you can change first SortDescription to sort by Length property

defaultView.SortDescriptions.Add(new SortDescription("Length", ListSortDirection.Ascending));
defaultView.SortDescriptions.Add(new SortDescription("", ListSortDirection.Descending));
dkozl
  • 32,814
  • 8
  • 87
  • 89