datagrid控件分页效果,如下图所示:

上一页,下一页,可以跳到任何一页。当页码比较多的时候,只显示几页,其余用点点,界面实现如下:

 <!--分页-->
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Grid.Row="" Margin="0 20" x:Name="fulltextPager"> <Button x:Name="prePage" Click="prePage_Click" Style="{StaticResource btnPager}" ToolTip="上一页"/> <Button Style="{StaticResource btnPager}" Content="" x:Name="bntGoFirstPage" Click="bntGoFirstPage_Click" /> <TextBlock x:Name="predot" Text="..." Visibility="{Binding PreVisible}"/> <ItemsControl ItemsSource="{Binding Pages}" x:Name="btnPagerContainer">
<ItemsControl.ItemTemplate>
<DataTemplate>
<WrapPanel>
<Button Style="{StaticResource btnPager}" Content="{Binding Name}" Click="btn_GotoPage" />
</WrapPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
<!--这里用WrapPanel 当容器放Button-->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate> <WrapPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> <TextBlock x:Name="nextdot" Text="..." Visibility="{Binding NextVisible}"/> <Button Style="{StaticResource btnPager}" Content="{Binding Total}" x:Name="btnGoLastPage" Click="btnGoLastPage_Click" /> <Button x:Name="nextPage" Click="nextPage_Click" Content=">>" Style="{StaticResource btnPager}" ToolTip="下一页"/> <TextBlock Text="当前"/>
<TextBlock Text="{Binding PageIndex}" Foreground="#3091f2"/>
<TextBlock Text="页"/> <TextBlock Text="跳转到" Style="{StaticResource pagerStyle}" Margin="5 0 5 0"/>
<TextBox x:Name="wantToGo" Width="" Height=""></TextBox>
<TextBlock Text="页" Style="{StaticResource pagerStyle}"/> <TextBlock Style="{StaticResource pagerStyle}"> <Button Content="go" x:Name="goPage" Click="goPage_Click" Style="{StaticResource btnPager}" /> </TextBlock> <TextBlock Style="{StaticResource pagerStyle}"> <TextBlock Text="共"/>
<TextBlock Text="{Binding ItemCount}" Foreground="#3091f2"/>
<TextBlock Text="条"/> </TextBlock> </StackPanel>

ItemsControl 是一个完全自定义的集合控件,它没有默认的形状,不像button,它默认为长方形。看看它的数据是如何绑定的?

this 代表了TestCaseUserControl ,这是个自定义的用户控件,它里面包含了datagrid控件以及分页。Data是个复杂的对象,包含了数据源以及一些分页支持。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading; namespace WpfReovlveTest
{
public class PageDataManager<T> : INotifyPropertyChanged
{
private int pageSize = ;
public int PageSize
{
get { return pageSize; }
set
{
pageSize = value;
NotifyPropertyChanged("PageSize");
}
} private int pageIndex;
public int PageIndex
{
get { return pageIndex; }
set
{
pageIndex = value;
NotifyPropertyChanged("PageIndex");
}
} private int total;
public int Total
{
get { return total; }
set
{
total = value;
NotifyPropertyChanged("Total");
}
} private Visibility preVisible = Visibility.Collapsed; public Visibility PreVisible
{
get { return preVisible; }
set
{
preVisible = value;
NotifyPropertyChanged("PreVisible");
}
} private Visibility nextVisible = Visibility.Collapsed; public Visibility NextVisible
{
get { return nextVisible; }
set
{
nextVisible = value;
NotifyPropertyChanged("NextVisible");
}
} private ObservableCollection<Pages> pages;
public ObservableCollection<Pages> Pages
{
get { return pages; }
set
{
pages = value;
NotifyPropertyChanged("Pages");
}
}
/// <summary>
/// 总数
/// </summary>
private int itemCount;
public int ItemCount
{
get { return itemCount; }
set
{
itemCount = value;
NotifyPropertyChanged("ItemCount");
}
} private ObservableCollection<T> dataSource; /// <summary>
/// 总的数据源
/// </summary>
public ObservableCollection<T> DataSource
{
get { return dataSource; }
set
{
dataSource = value;
NotifyPropertyChanged("DataSource");
}
} private ObservableCollection<T> pagerSource = new ObservableCollection<T>(); /// <summary>
/// 每页的数据源
/// </summary>
public ObservableCollection<T> PagerSource
{
get { return pagerSource; }
set
{
pagerSource = value;
NotifyPropertyChanged("PagerSource");
}
} public Action<int, int> PagerOp; public bool IsMemoryPager { set; get; } //负责监视属性的变化
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string Propertyname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(Propertyname));
}
} /// <summary>
/// 打开等待窗口
/// </summary>
public Action OpenWaitingWindow { set; get; }
/// <summary>
/// 关闭等待窗口
/// </summary>
public Action CloseWaitingWindow { set; get; } public UIElement Owner { get; set; } public PageDataManager(ObservableCollection<T> source, int count, bool isMemoryPager = true, Action<int, int> PagerOp = null, int pageSize = , int pageIndex = )
{
this.PageSize = pageSize;
this.DataSource = source;
this.ItemCount = count;
this.Total = this.ItemCount % PageSize == ? ItemCount / PageSize : ItemCount / PageSize + ; this.PagerOp = PagerOp; this.PageIndex = pageIndex; this.IsMemoryPager = isMemoryPager; Pager(this.PageIndex, false);
} private void MakePagerNum()
{
//初始化页数数组
if (this.Pages == null)
{
this.Pages = new ObservableCollection<Pages>();
}
else
{
this.Pages.Clear();
} this.PreVisible = Visibility.Collapsed;
this.NextVisible = Visibility.Collapsed; if (this.Total > )
{
//以当前页为分界点,向左借2个,向右借2个 int leftLength = this.PageIndex - ;
int rightLength = this.Total - this.PageIndex; if (leftLength > && rightLength > )
{
this.PreVisible = Visibility.Visible; for (int i = PageIndex - ; i <= PageIndex + ; i++)
{
this.Pages.Add(new Pages() { Name = i.ToString(), PageIndex = i });
}
this.NextVisible = Visibility.Visible;
} if (rightLength <= )
{
//右边的不够,向左边借
this.PreVisible = Visibility.Visible; for (int i = this.PageIndex - ( - rightLength); i <= this.Total - ; i++)
{
this.Pages.Add(new Pages() { Name = i.ToString(), PageIndex = i });
}
}
if (leftLength <= )
{
//左边的不够,向右边借
for (int i = ; i <= this.PageIndex + ( - leftLength); i++)
{
this.Pages.Add(new Pages() { Name = i.ToString(), PageIndex = i });
}
this.NextVisible = Visibility.Visible;
}
}
else
{
for (int i = ; i <= Total - ; i++)
{
this.Pages.Add(new Pages() { Name = i.ToString(), PageIndex = i });
}
}
} private void PagerOpCompleted(IAsyncResult result)
{
try
{
var handler = (Action<int, int>)((AsyncResult)result).AsyncDelegate;
handler.EndInvoke(result); if (this.Owner != null)
{
this.Owner.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(ThreadStart)delegate()
{
FillPagerSource();
});
}
}
catch (Exception ex)
{
MessageBox.Show("异步分页出错:" + ex.Message);
}
finally
{
//关闭等待图标
if (this.Owner != null)
{
this.Owner.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(ThreadStart)delegate()
{
if (CloseWaitingWindow != null)
{
CloseWaitingWindow();
}
});
}
}
}
public void Pager(int pageIndex, bool canPager = true)
{
if (pageIndex < || pageIndex > this.Total)
{
return;
}
this.PageIndex = pageIndex; MakePagerNum(); if (PagerOp != null && canPager)
{
//委托异步执行 IAsyncResult result = PagerOp.BeginInvoke(this.PageSize, pageIndex, new AsyncCallback(PagerOpCompleted), null); //打开等待图标 if (OpenWaitingWindow != null)
{
OpenWaitingWindow();
}
}
else
{
FillPagerSource();
}
} private void FillPagerSource()
{
IEnumerable<T> pagerDatas = DataSource; if (this.IsMemoryPager)
{
List<T> tempSource = new List<T>();
tempSource.AddRange(this.DataSource);
pagerDatas = tempSource.Skip((this.PageIndex - ) * PageSize).Take(this.PageSize);
} this.PagerSource.Clear(); foreach (var item in pagerDatas)
{
this.PagerSource.Add(item);
}
}
}
} public class Pages
{
public string Name { get; set; }
public int PageIndex { get; set; }
}

分页类

这是一个通用的wpf分页类,即可用给datagrid使用,也可以给ListView使用。使用方法如下:

        public void SetSource(ObservableCollection<TestCaseListViewModel> models, int itemCount, bool isMemoryPager, int pageIndex = )
{
this.FullTextList = models;
this.Data = new PageDataManager<TestCaseListViewModel>(FullTextList, itemCount, isMemoryPager, this.PagerFullTask, PageSize, pageIndex); this.Data.OpenWaitingWindow = OpenWaitingWindow;
this.Data.CloseWaitingWindow = CloseWaitingWindow;
this.Data.Owner = this; this.DataContext = Data;
this.TestCaseDataGrid.DataContext = Data.PagerSource; fulltextPager.Visibility = itemCount == ? Visibility.Collapsed : Visibility.Visible; prePage.Content = "<<";
btnGoLastPage.Visibility = Data.Total == ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible; }

在自定义的用户控件中,实例化分页类,参数说明如下:

FullTextList:数据源

itemCount:总数

isMemoryPager:是否内存分页(false:数据库分页)

PagerFullTask:获取每页数据源的方法

这个数据分页类与具体的控件无关,它只与数据源相关。

wpf研究之道——datagrid控件分页的更多相关文章

  1. wpf研究之道-datagrid控件(1)

    "想要说些什么 又不知从何说起",每当想要写一些关于wpf的文章,总是沉思良久,怕自己写不好.今天我想要说的是wpf中datagrid控件.我们先来看看它在整个类的层次结构:   ...

  2. wpf研究之道——datagrid控件数据绑定

    前台: <DataGrid x:Name="TestCaseDataGrid" ItemsSource="{Binding}" > {binding ...

  3. wpf研究之道-grid控件

    想要说些什么,却不知道从哪开始."形而上谓之道,形而下谓之器".与其坐而论道,不如脚踏实地,从最实用的地方开始. 我们先来看看wpf中的grid控件.grid控件是个网格的布局控件 ...

  4. WPF:获取DataGrid控件单元格DataGridCell

    转载:http://blog.csdn.net/jhqin/article/details/7645357 /* ------------------------------------------- ...

  5. WPF的DataGrid控件从excel里复制数据然后粘贴

    WPF的DataGrid控件不能像winform的DataGridView控件一样,支持值的粘贴.WPF的DataGrid控件本质上是跟数据绑定联系在一起,所以需要进行复制粘贴的操作,可以在wpf里用 ...

  6. WPF DataGrid 控件的运用

    WPF DataGrid 控件的运用 运行环境:Window7 64bit,.NetFramework4.61,C# 6.0: 编者:乌龙哈里 2017-02-23 参考: King Cobra 博客 ...

  7. C# WPF DataGrid控件实现三级联动

    利用DataGrid控件实现联动的功能,在数据库客户软件中是随处可见的,然而网上的资料却是少之又少,令人崩溃. 本篇博文将介绍利用DataGrid控件模板定义的三个ComboBox实现“省.市.区”的 ...

  8. WPF 4 DataGrid 控件(进阶篇一)

    原文:WPF 4 DataGrid 控件(进阶篇一)      上一篇<WPF 4 DataGrid 控件(自定义样式篇)>中,我们掌握了DataGrid 列表头.行表头.行.单元格相关的 ...

  9. WPF 4 DataGrid 控件(进阶篇二)

    原文:WPF 4 DataGrid 控件(进阶篇二)      上一篇<WPF 4 DataGrid 控件(进阶篇一)>中我们通过DataGridTemplateColumn 类自定义编辑 ...

随机推荐

  1. 智能合约语言 Solidity 教程系列8 - Solidity API

    这是Solidity教程系列文章第8篇介绍Solidity API,它们主要表现为内置的特殊的变量及函数,存在于全局命名空间里. 写在前面 Solidity 是以太坊智能合约编程语言,阅读本文前,你应 ...

  2. log4net应用实践(一)

          1.背景 log4net库是Apache log4j框架在Microsoft .NET平台的实现,是一个帮助程序员将日志信息输出到各种目标(控制台.文件.数据库等)的工具.它是.Net下一 ...

  3. Tencent研发工程师笔试知识点

      一: 32位编译器:32位系统下指针占用4字节       char :1个字节       char*(即指针变量): 4个字节(32位的寻址空间是2^32, 即32个bit,也就是4个字节.同 ...

  4. MongoDB起步

    1.Mongodb基本概念和SQL的区别:SQL术语        MongoDB术语database    databasetable        collectionrow        doc ...

  5. eclipse的注释

    版权声明:本文为博主原创文章,转载请注明出处. 如果能帮助你,那我的目的就达到了 Window --> Java --> Code Style --> Code Templates ...

  6. C++实验指导

    选择 Build > Set Active Configuration 菜单,在对话框中选择 Win32 Debug. 当程序调试成功后,一般将其生成发布版,这样可使运行程序优化,方法是在上述对 ...

  7. Pythonic

    这个词翻译过来就是 这很python,其产生的目的就是写出更简洁的,没有冗余的python代码. 1.元素交换 a, b = b, a 看到网上有人解释的很好,首先,建立元组的重点不在于括号'()', ...

  8. jq 抽奖转盘

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. CSS( Cascading Style Sheets )简书

    (注:带*号的属性是CSS3新增属性)一.基本规则1.css通常存储在样式表(style)中,用于定义如何显示HTML元素:2.css主要由两个部分构成:选择器和一条或多条声明. 选择器通常是需要改变 ...

  10. Mycat 介绍

    Mycat 是什么 Mycat是什么?从定义和分类来看,它是一个开源的分布式数据库系统,是一个实现了 MySQL协议的的Server,前端用户可以把它看作是一个数据库代理,用 MySQL客户端工具和命 ...