代码改变世界

在Silverlight修改DataPager控件以实现自定义分页功能

2011-04-24 21:38  三夏  阅读(1070)  评论(5编辑  收藏  举报

Silveright中提供了DataPager控件以实现分页功能,其具体实现方式如下所示:

private void BindDataSource()
{
     List<string> dataCollection = new List<string>();     
     for (int i = 0; i < 1000; i++)
     {
          dataCollection.Add(i.ToString());
     }

     PagedCollectionView pagedCollectionView = new PagedCollectionView(dataCollection);
     dgResult.ItemsSource = pagedCollectionView;
     dpResult.PageCount = dataCollection.Count;
}

但以上这种方法在碰到大批量数据则会碰到严重的性能问题。 因此,笔者想到传统的WEB页面中分页的方法,尝试在Silverlight中实现类似传统的分面功能。经过多方查找资料并尝试,可用以下思路实现传统的分页功能,即从服务端获取到分页的记录集,再得到符合条件的记录集总数,然后构造一个数据集合,该数据集合数量等于查询结果总数并将其绑定到DataPager控件,并且将得到的分页结果绑定到DataGrid。当页面PageIndex变换时,引发事件从服务端获取相应PageIndex的记录集。在具体实现过程中,可以将DataGrid和DataPager控件封装成一个分页控件。其具体实现方法如下:

CustomDataPager : DataPager
{
     private DependencyProperty m_pageIndex = DependencyProperty.Register(&quot;PageCount&quot;, typeof(int), typeof(CustomDataPager), new PropertyMetadata(PropertyChangedCallbackHandler));

     public new int PageCount
     {
    	 get
         {
             return (int)this.PageIndex + 1;
         }
         set
         {
             this.SetValue(m_pageIndex, value);
         }
     }

     private static void PropertyChangedCallbackHandler(DependencyObject d, DependencyPropertyChangedEventArgs e)
     {
      	 CustomDataPager customDataGrid = d as CustomDataPager;
       	 if (customDataGrid != null)
     	 {
             List<int> list = new List<int>;();
             int recordCount = (int)e.NewValue;
             for (int i = 0; i < recordCount; i++)
             {
            	 list.Add(i);
             }

             PagedCollectionView pagedCollectionView = new PagedCollectionView(list);
             customDataGrid.Source = pagedCollectionView;
       	 }
     }
     public CustomDataPager()
     {
    	 InitializeComponent();
     }
}

然后在自定义的DataGrid中调用即可:

private void BindDataSource()
{
     List<string> dataCollection = new List<string>();
     for (int i = 0; i < 1000; i++)
     {
      	 dataCollection.Add(i.ToString());
     }

     PagedCollectionView pagedCollectionView = new PagedCollectionView(dataCollection);
     dgResult.ItemsSource = pagedCollectionView;
     dpResult.PageCount = dataCollection.Count;
}