【问题标题】:Items inside Groups in ICollectionView are not sortedICollectionView 中 Groups 内的项目未排序
【发布时间】:2016-04-16 17:25:51
【问题描述】:

我有一个ObservableCollection<string>

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

Window 中的ListBox 绑定到此集合。在 Window Loaded 事件中,我将排序和分组逻辑分配给 Collection 的底层 ICollectionView。

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 在其转换方法中返回字符串的长度。

结果如下:

我希望组按升序排序,其中的项目按降序排序。但似乎没有使用组内项目的SortDescription - 它没有按降序排序。

我不确定我做错了什么。

【问题讨论】:

  • 获取字符串的第一个字母:collection.OrderBy(x&gt;x.Substring(0,1))
  • @MaciejLos,我不明白。 SortDescription 对字符串使用默认比较器。
  • @EmperorAiman 您是否尝试先将SortDescription 更改为new SortDescription("Length", ListSortDirection.Ascending),所以主要排序是按项目长度?
  • @dkozl,啊。是的。这解决了问题。我认为第一个 sortdescription 使用 CollectionViewGroups.Name 进行排序。我的错。所以排序独立于分组。谢谢。如果你愿意,你可以把它变成一个答案。我会接受的。

标签: c# wpf sorting icollectionview


【解决方案1】:

所有排序描述都适用于项目,即使您使用分组并且您有两个具有相同属性的排序描述。不幸的是,您不能按转换后的值排序,但您可以先将SortDescription 更改为按Length 属性排序

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多