zoukankan      html  css  js  c++  java
  • 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

     






  • 相关阅读:
    15.手写数字识别-小数据集(load_digits)
    14.深度学习-卷积
    13-垃圾邮件分类2
    12.朴素贝叶斯-垃圾邮件分类
    11.分类与监督学习,朴素贝叶斯分类算法
    9.主成分分析
    关于core_UI的安装和使用
    2020系统综合实践 期末大作业 15组
    2020系统综合实践 第7次实践作业 26组
    第6次实践作业
  • 原文地址:https://www.cnblogs.com/stswordman/p/615092.html
Copyright © 2011-2022 走看看