How do I sort groups of data items?(WPF)



 今天我要介绍如何使用CollectionViewSource对数据进行分组以及对各个组进行排序

 
示例中的数据源是一组类型为Animal的对象组成的数据集合。Animal类包含NameCategory(枚举类型)两个属性。现在要以Category为分组来显示数据:
    <Window.Resources>
        <local:Animals x:Key="animals"/>

        <CollectionViewSource x:Key="cvs" Source="{Binding Source={StaticResource animals}, Path=AnimalList}">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="Category"/>
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>

        <DataTemplate x:Key="animalTemplate">
            <TextBlock Text="{Binding Path=Name}" Foreground="MediumSeaGreen"/>
        </DataTemplate>
    </Window.Resources>

    <ItemsControl ItemsSource="{Binding Source={StaticResource cvs}}" ItemTemplate="{StaticResource animalTemplate}"/>

我在上一篇文章中介绍过CollecitonViewSourceCollectionViewSource类会在数据源的上层生成一个视图。这个视图监控着选中项,并且允许我们对数据项进行分组,排序和过滤

运行上面的代码后,可以看到动物的名称,但分组信息没有显示出来。接下来要创建一个显示分组信息的模板。CollectionViewSource将每个分组都包装到CollectionViewGroup对象中。然后显示其Name属性即可:

    <DataTemplate x:Key="categoryTemplate">
        <TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Foreground="ForestGreen" Margin="0,5,0,0"/>
    </DataTemplate>

接下来让ItemsControl控件的GroupStyle属性应用上面的模板:
    <ItemsControl ItemsSource="{Binding Source={StaticResource cvs}}">
        <ItemsControl.GroupStyle>
            <GroupStyle HeaderTemplate="{StaticResource categoryTemplate}" />
        </ItemsControl.GroupStyle>
    </ItemsControl>


如果需要显示多级别的分组,可以添加多个GroupStyle(示例中只添加了一个)

现在,程序已经可以正确地显示分组和各个项目了。如果还要实现组的排序,并对组内的项进行排序该怎么作呢?我看到有人想写个类似于”SortGroups”的方法来实现这个功能。实际上不必这么做,只要对“进行了分组的属性”进行排序就可以实现这个功能:
    <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>

 
有一点需要注意:Category是一个枚举类型,所以“组排序”的顺序是根据其在枚举中定义的顺序。而Name属性是字符串类型,所以“组内排序”是根据字母顺序

程序截图: 



原文地址:http://www.beacosta.com/Archive/2006_01_01_bcosta_archive.html

 






posted on 2007-01-08 18:32  stswordman  阅读(1752)  评论(0编辑  收藏  举报