How can I order Groups in WPF

后端 未结 2 454
攒了一身酷
攒了一身酷 2020-12-20 11:52

In WPF, the CollectionViewSource allows for sorting (SortDescriptions) and grouping (GroupDescriptions). However, I can\'t find a way to order the groups. Is it possible?

相关标签:
2条回答
  • 2020-12-20 12:36

    Groups sorting is possible though it's not so straightforward. I'll explain it on the example.

    class CollectionElement
    {
         public string Name {get; set; }
         public string Group {get; set; }
    }
    

    If you wish to group elements and sort the groups alphabetically then sort elements within each group alphabetically then you should do the following:

    1. Add PropertyGroupDescription referencing Group property
    2. Add SortDescription referencing Group
    3. Add SortDescription referencing Name

    The grouping process seems to work effectively like the following way: Iterate through already sorted elements consequently. When encountering element form unknown group - create a group and add it to groups list. When encountering element from existing group - add it to the existing group. (Actual implementation may be different). So if your elements are sorted in the order you wish your groups to appear you will effectively sort the groups.

    0 讨论(0)
  • 2020-12-20 12:43
    <CollectionViewSource x:Key="cvs" Source="{Binding Source={StaticResource animals}, Path=AnimalList}">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="Category"/>
        </CollectionViewSource.GroupDescriptions>
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Category" />
            <scm:SortDescription PropertyName="Name" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
    

    Just add two SortDescriptions.Adding two sort descriptions allows us to sort the groups first and then the items within the groups.

    For more check here

    http://bea.stollnitz.com/blog/?p=17

    0 讨论(0)
提交回复
热议问题