在WPF中想要自己去写一个可以实现分页的功能,为了避免页面有一次过多显示数据,如果数据量大,那么难免要使用到分页的功能于数据表格,避免一次性显示过多的数据。
XAML:
对于按钮我们需要初始化,
思路:1、对于一开始加载数据拥有事先设计好的需要加载出来的条数,上图中的每页页数就是控制数据显示条数的,
这是一个下拉框,我们可以给它设置内容,比如初始化显示十条数据,但是用户想要每页显示其它条数的数据,可以通过更改它实现。
2、按钮的初始化主要是针对刚刚加载如页面时,默认处于第一页,那么首页按钮和上一页的按钮就要被禁用,尾页按钮和下一页按钮启用(注意:这两个是否启用还得判断数据的条数要大于默认情况下的每页的页数,不然没有下一页,就不需要启用)。
代码实现如下:
//首页、上一页、尾页、下一页按钮初始化
public void UpdatePagingButton()
{
//如果是首页,则把上一页和首页按钮禁用(样式)
if (Convert.ToInt32(txtCurrentPage.Text) <= 1)
{
//禁用首页、上一页
imgMostUp.Opacity = 0.3;
imgMostUp.Cursor = Cursors.Arrow;
imgUp.Opacity = 0.3;
imgUp.Cursor = Cursors.Arrow;
}
else
{
//启用首页、上一页
imgMostUp.Opacity = 1;
imgMostUp.Cursor = Cursors.Hand;
imgUp.Opacity = 1;
imgUp.Cursor = Cursors.Hand;
}
if (Convert.ToInt32(txtCurrentPage.Text) >= Convert.ToInt32(lblMaxPage.Content))//如果是尾页,则把下一页和尾页按钮禁用(样式)
{
//禁用首页、上一页
imgMostDown.Opacity = 0.3;
imgMostDown.Cursor = Cursors.Arrow;
imgDown.Opacity = 0.3;
imgDown.Cursor = Cursors.Arrow;
}
else
{
//启用首页、上一页
imgMostDown.Opacity = 1;
imgMostDown.Cursor = Cursors.Hand;
imgDown.Opacity = 1;
imgDown.Cursor = Cursors.Hand;
}
}
实现分页的查询方法:
思路:
1、先要查询出数据,只有知道了数据的条数才能计算出分页的页数,分页数=查询出来的数据条数/每页页数,
2、二获取到每页显示的数据条数,通过这个参数确定从查询出来的数据里面分割需要显示的数据出来,用于绑定到页面上去
// 分页查询方法
DataTable ChaXunShuJu(int intPageLineCount, int intCurrentPage, bool bolSeleteSum, bool bolInvertedOrder)
{
if (txtSelectContent.Text != “”)
{
//累加模糊查询内容
strWhere = “line_name like ‘%’+’” + txtSelectContent.Text.Trim() + “’+’%’” +
" or simple_code like ‘%’+’" + txtSelectContent.Text.Trim() + “’+’%’” +
" or note like ‘%’+’" + txtSelectContent.Text.Trim() + “’+’%’”;
}
else if (txtSelectContent.Text == “” || txtSelectContent.Text == string.Empty)
{
strWhere = “1=1”;
}
//获取查询结果的行数
decPageCount = Convert.ToDecimal(myFunctionClient.PublicPagingSelect(strTblName, strGetFields, strFldName, intPageSize, intPageIndex, true, true, strWhere).Tables[0].Rows[0][0]);
//判断有多少页
if (decPageCount / intPageLineCount <= Convert.ToInt32(decPageCount / intPageLineCount))
{
//得到最新总页数(条件)
decPageCount = Convert.ToInt32(decPageCount / intPageLineCount);
}
else
{
//默认
decPageCount = Convert.ToInt32(decPageCount / intPageLineCount) + 1;
}
if (intCurrentPage > decPageCount)//如果当前页数大于最大页数,则重新赋值为最大页数
{
//当前页最大页
intPageIndex = (int)decPageCount;
intCurrentPage = (int)decPageCount;
}
if (intPageIndex == 0 || intCurrentPage == 0)//如果当前页数为0,则重新赋值为1
{
//当前页1
intPageIndex = 1;
intCurrentPage = 1;
}
lblMaxPage.Content = decPageCount.ToString();//给最大页数赋值
txtCurrentPage.Text = intCurrentPage.ToString();//给当前页数文本框赋值
//分页得到的Data
return myFunctionClient.PublicPagingSelect(strTblName, strGetFields, strFldName, intPageLineCount, intCurrentPage, bolSeleteSum, bolInvertedOrder, strWhere).Tables[0];//返回查询出来的结果
}
注意:代码来源于李老师授课