Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1017613
  • 博文数量: 243
  • 博客积分: 3053
  • 博客等级: 中校
  • 技术积分: 2975
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-02 21:11
文章分类

全部博文(243)

文章存档

2013年(2)

2012年(20)

2011年(5)

2010年(114)

2009年(102)

我的朋友

分类:

2010-09-15 15:41:34

最近项目中一直在和PagedCollectionView这个类打交道。通过它,我们可以以分页的形式自动处理并显示集合中的片段,尤其是和Pager控件配合的时候更能彰显其威力。

  PagedColectionView类实现了ICollectionView接口,因此除分页外,它也同时提供了的其他一些对集合操作非常有用功能,如

  Sorting 排序

  Filtering 过滤

  Grouping 分组

  我们用一个简单的DataGrid演示这些功能。

  首先创建一个超简单的实体类

  public class Person { 
    public string FullName { get; set; } 
    public int? Age { get; set; } 
  }

  接着构造一个List

      var peopleList = new List { 
        new Person(){ FullName="forever",Age=13 }, 
        new Person(){ FullName="fish",Age=14}, 
        new Person(){ FullName="SBPP",Age=40}, 
        new Person(){FullName="TNT",Age=null}, 
        new Person(){FullName="SARS",Age=5} 
      };

  然后后创建一个PagedCollectionView的新实例,并以上面创建的Person集合作为其构造函数的参数:

  PagedCollectionView pcv = new PagedCollectionView(peopleList);

  现在让我们看一下如何通过PagedCollectionView简单的针对集合进行排序

  ICollectionView接口定义了一个SortDescriptions集合,用以设置视图的排序规则,比如:要让我们的Person集合先按照年龄(Age)正序排列再按照全名(FullName)倒序排列,我们可以通过添加两个SortDescription对象来完成这个需求:

pcv.SortDescriptions.Clear(); 
 
var sortDescription1 = new System.ComponentModel.SortDescription("Age", System.ComponentModel.ListSortDirection.Ascending); 
var sortDescription2 = new System.ComponentModel.SortDescription("Age", System.ComponentModel.ListSortDirection.Ascending); 
 
pcv.SortDescriptions.Add(sortDescription1); 
pcv.SortDescriptions.Add(sortDescription2);

  F5运行后:

Silverlight中的PagedCollectionView

  ICollectionView同时也提供了分组功能。和排序一样,我们只需添加GroupDescription对象到 GroupDescription中即可。当前GroupDescription只提供实现一种分组方式--即通过属性名分组(PropertyGroupDescription)。

  我们实体类中加入一个Gender属性标识性别

  public class Person { 
    public string FullName { get; set; } 
    public int? Age { get; set; } 
    public string Gender { get; set; } 
  }

  接着修改我们的Person集合

      var peopleList = new List { 
        new Person(){ FullName="forever",Age=13,Gender="男" }, 
        new Person(){ FullName="fish",Age=14,Gender="公"}, 
        new Person(){ FullName="SBPP",Age=40,Gender="男"}, 
        new Person(){FullName="TNT",Age=null,Gender="男"}, 
        new Person(){FullName="SARS",Age=5,Gender="无"}, 
        new Person(){FullName="Lulu",Age=18,Gender="女"} 
      };

  最后,添加分组规则

  pcv.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));

  F5运行后:

Silverlight中的PagedCollectionView

  最后要介绍的就是PagedCollectionView通过实现

  ICollectionView

  接口提供的任意筛选的能力。

  用于筛选的Filter属性为

  Predicate

  类型,因此我们可以简单的通过Lambda表达式进行集合项的筛选,比如我们要筛选集合中属性Gender为“男”的Person:

  pcv.Filter = p => ((Person)p).Gender.Equals("男");  

  运行后效果如下

Silverlight中的PagedCollectionView

  够酷够方便吧。

 

阅读(1713) | 评论(0) | 转发(0) |
0

上一篇: 简单容器(转)

下一篇:画刷

给主人留下些什么吧!~~