基于Group ItemCount对组进行排序

时间:2012-01-02 15:16:58

标签: wpf sorting grouping listcollectionview

ListCollectionView上,我只需添加新的GroupDescriptions。 但我正在寻找一种基于组ItemCount对它们进行排序的方法。

因此,在第一个位置,我会得到最多的项目组。

2 个答案:

答案 0 :(得分:3)

您可以将组包装在另一个视图中并对其进行排序。

XAML示例:

<CollectionViewSource x:Key="Items2" Source="{Binding Groups,
                                                      Source={StaticResource Items}}">
    <CollectionViewSource.SortDescriptions>
        <cm:SortDescription PropertyName="ItemCount" Direction="Descending"/>
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

答案 1 :(得分:0)

我已经创建了一个自定义ListCollectionView,可以使用一个很棒的库System.Linq.Dynamic进行顶级组排序:

Public Class ListCollectionViewEx
    Inherits ListCollectionView
    Private _groupSortDescriptions As SortDescriptionCollection
    Private _groups As ReadOnlyObservableCollection(Of Object)

    Public Overridable ReadOnly Property GroupSortDescriptions As SortDescriptionCollection
        Get
            Return Me._groupSortDescriptions
        End Get
    End Property

    Public Overrides ReadOnly Property Groups As System.Collections.ObjectModel.ReadOnlyObservableCollection(Of Object)
        Get
            If Me._groupSortDescriptions.Count > 0 Then
                If Me._groups Is Nothing AndAlso
                    MyBase.Groups IsNot Nothing Then
                    Dim qs As String = String.Join(
                        ",",
                        Me._groupSortDescriptions.
                        Select(Function(gsd) String.Format("{0} {1}", gsd.PropertyName, If(gsd.Direction = ListSortDirection.Ascending, "ASC", "DESC"))).
                        ToArray)

                    Dim sortedGroups = MyBase.Groups.
                        Select(Function(g) DirectCast(g, CollectionViewGroup)).
                        AsQueryable.OrderBy(qs).
                        AsEnumerable

                    If sortedGroups IsNot Nothing AndAlso
                        sortedGroups.Count > 0 Then
                        Me._groups = New ReadOnlyObservableCollection(Of Object)(New ObservableCollection(Of Object)(sortedGroups))
                    End If
                End If

                Return Me._groups
            End If

            Return MyBase.Groups
        End Get
    End Property

    Public Sub New(collection As IEnumerable)
        MyBase.New(collection)
        Me._groupSortDescriptions = New SortDescriptionCollection()
    End Sub
End Class

用法:

View.GroupSortDescriptions.Add(New SortDescription("ItemCount", ListSortDirection.Descending))