最近用到WPF的表格控件,需要使用分页功能,找了很多例子都不是很满意。有些是模仿SL做的DataPager导航条,使用的时候还要和DataGrid组合使用,不是很方便。最好还是继承DataGrid的分页表格控件。 于是自己动手封装了一个分页表格。 见图例:
先说思路,然后说实现。 为什么要使用分页这里不是讨论话题,分页表格需要知道两个结果:总记录数和分页数据集,所以必须暴露Total和ItemsSource属性,要查询分页必须传递:页面和每页记录数。 1.分页表格是一个DataGrid,所以继承于DataGrid; 2.添加一些依赖属性,比如:页面、每页记录数等,允许用户自定义设置属性; 3.重写样式,在样式模板中添加分页导航控件; 4.暴露分页事件,用户分页逻辑在事件中实现。 说起来很容易,做起来没一个很容易的。为了分页导航按钮漂亮,我还做了一个ImageButton的用户控件(这里不介绍此控件)
看看部分实现: 1.定义表格模板(比较复杂,不具体一一说明了) 关键在ControlTemplate中加入一个Grid,就是导航控件部分,注意我的绑定方式,不是TemplateBinding。
2.分页表格类(部分代码,完整见下载中的代码) 其中定义了一些依赖属性,如:PageIndex、PageSize、Total等
public class PagingDataGrid : DataGrid { static PagingDataGrid() { DefaultStyleKeyProperty.OverrideMetadata(typeof(PagingDataGrid), new FrameworkPropertyMetadata(typeof(PagingDataGrid))); } #region 依赖属性 public int Total { get { return (int)GetValue(TotalProperty); } set { SetValue(TotalProperty, value); } } /// /// 总记录数 /// public static readonly DependencyProperty TotalProperty = DependencyProperty.Register('Total', typeof(int), typeof(PagingDataGrid), new UIPropertyMetadata(0)); public int PageSize { get { return (int)GetValue(PageSizeProperty); } set { SetValue(PageSizeProperty, value); } } /// /// 每页记录数,默认:10 /// public static readonly DependencyProperty PageSizeProperty = DependencyProperty.Register('PageSize', typeof(int), typeof(PagingDataGrid), new UIPropertyMetadata(10)); public int PageIndex { get { return (int)GetValue(PageIndexProperty); } set { SetValue(PageIndexProperty, value); } } /// /// 当前页码,默认:1 /// public static readonly DependencyProperty PageIndexProperty = DependencyProperty.Register('PageIndex', typeof(int), typeof(PagingDataGrid), new UIPropertyMetadata(1)); public static readonly RoutedEvent PagingChangedEvent = EventManager.RegisterRoutedEvent('PagingChangedEvent', RoutingStrategy.Bubble, typeof(PagingChangedEventHandler), typeof(PagingDataGrid)); #endregion #region 重写方法 public override void OnApplyTemplate() { base.OnApplyTemplate(); //获取模板中的控件 //添加控件事件 } #endregion #region 分页事件 #endregion}
3.用户界面使用,和DataGrid一样使用,增加几个属性就行了
4.分页实现,只需要触发事件PagingDataGrid_PagingChanged事件即可
/// /// MainWindow2.xaml 的交互逻辑 /// public partial class MainWindow2 : Window { public MainWindow2() { Result = new StuResult(); InitializeComponent(); } public StuResult Result { get; set; } public void Query(int size, int pageIndex) { Result.Total = Student.Students.Count; Result.Students = Student.Students.Skip((pageIndex - 1) * size).Take(size).ToList(); } private void PagingDataGrid_PagingChanged(object sender, CustomControlLibrary.PagingChangedEventArgs args) { Query(args.PageSize, args.PageIndex); } }
代码见我的资源中,下载地址:http://download.csdn.net/detail/qing2005/4337197。
|