WPF 自定义分页控件DataPager.xaml
来源:互联网 发布:linux教程孟庆昌答案 编辑:程序博客网 时间:2024/06/06 19:30
1、DataPager.xaml
<UserControl x:Class="Client.UserControls.DataPager" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="30" d:DesignWidth="850"> <UserControl.Resources> <Style x:Key="gridIcon" TargetType="TextBlock"> <Setter Property="FontFamily" Value="iconfont"></Setter> <Setter Property="Foreground" Value="#FF3498CE"></Setter> <Setter Property="Padding" Value="5,7,5,5"></Setter> <Setter Property="Cursor" Value="Hand"></Setter> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Foreground" Value="#FFA336"></Setter> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="#ccc"></Setter> </Trigger> </Style.Triggers> </Style> <Style x:Key="pageNumber" TargetType="TextBlock"> <Setter Property="Padding" Value="5,5,5,5"></Setter> <Setter Property="Foreground" Value="#FF3498CE"></Setter> <Setter Property="Cursor" Value="Hand"></Setter> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Foreground" Value="#FFA336"></Setter> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="#FF02486E"></Setter> </Trigger> </Style.Triggers> </Style> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="400"></ColumnDefinition> <ColumnDefinition MinWidth="450"></ColumnDefinition> </Grid.ColumnDefinitions> <WrapPanel Grid.Column="0" VerticalAlignment="Center"> <TextBlock Padding="5,5,5,5" Foreground="#FF02486E">当前显示第</TextBlock> <TextBlock Name="PageIndexNumber" Padding="5,5,5,5" Foreground="#FF3498CE"></TextBlock> <TextBlock Padding="5,5,5,5" Foreground="#FF02486E">页,每页</TextBlock> <TextBlock Name="PageNumber" Padding="5,5,5,5" Foreground="#FF3498CE">20</TextBlock> <TextBlock Padding="5,5,5,5" Foreground="#FF02486E">条/共</TextBlock> <TextBlock Name="TotalNumber" Padding="5,5,5,5" Foreground="#FF3498CE">49</TextBlock> <TextBlock Padding="5,5,5,5" Foreground="#FF02486E">条</TextBlock> </WrapPanel> <WrapPanel Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right"> <TextBlock Name="BtnFirst" Style="{StaticResource gridIcon}" IsEnabled="False"></TextBlock> <TextBlock Name="BtnPrev" Style="{StaticResource gridIcon}" IsEnabled="False"></TextBlock> <Grid Name="GridGrid"> <StackPanel Orientation="Horizontal"> <TextBlock Style="{StaticResource pageNumber}">1</TextBlock> <TextBlock Style="{StaticResource pageNumber}">2</TextBlock> <TextBlock Style="{StaticResource pageNumber}">3</TextBlock> <TextBlock Style="{StaticResource pageNumber}">4</TextBlock> <TextBlock Style="{StaticResource pageNumber}">5</TextBlock> <TextBlock Style="{StaticResource pageNumber}">6</TextBlock> <TextBlock Style="{StaticResource pageNumber}">7</TextBlock> <TextBlock Style="{StaticResource pageNumber}">8</TextBlock> <TextBlock Style="{StaticResource pageNumber}">9</TextBlock> </StackPanel> </Grid> <TextBlock Name="BtnNext" Style="{StaticResource gridIcon}" IsEnabled="False"></TextBlock> <TextBlock Name="BtnLast" Style="{StaticResource gridIcon}" IsEnabled="False"></TextBlock> </WrapPanel> </Grid></UserControl>
2、DataPager.xaml.cs
using System;using System.Data;using System.Windows;using System.Windows.Controls;using System.Windows.Input;namespace Client.UserControls{ /// <summary> /// DataPager.xaml 的交互逻辑 /// </summary> public partial class DataPager : UserControl { public DataPager() { InitializeComponent(); this.Loaded += delegate { //首页 this.BtnFirst.MouseLeftButtonUp += btn_First_Click; this.BtnFirst.MouseLeftButtonDown += btn_First_MouseLeftButtonDown; //上一页 this.BtnPrev.MouseLeftButtonUp += btn_Prev_Click; this.BtnPrev.MouseLeftButtonDown += btn_Prev_MouseLeftButtonDown; //下一页 this.BtnNext.MouseLeftButtonUp += btn_Next_Click; this.BtnNext.MouseLeftButtonDown += btn_Next_MouseLeftButtonDown; //末页 this.BtnLast.MouseLeftButtonUp += btn_Last_Click; this.BtnLast.MouseLeftButtonDown += btn_Last_MouseLeftButtonDown; }; } private DataTable _dt = new DataTable(); private int _pageNum;//每页显示条数 // private int _pageIndex = 1;//当前页码 public int _pageIndex = 1;//当前页码 private int _maxIndex = 1;//总页数 private int _totalNum = 0;//总条数 private DataGrid _dg; #region 初始化数据 public void ShowPages(DataGrid datagrid, DataTable datatable, int num) { if (datatable != null&&datatable.Rows.Count>0) { this._dt = datatable.Clone(); this._dg = datagrid; this._pageNum = num; this._pageIndex = 1; this._totalNum = datatable.Rows.Count; if ((datatable.Rows.Count % num) == 0) { this._maxIndex = datatable.Rows.Count / num; } else { this._maxIndex = (datatable.Rows.Count / num) + 1; } foreach (DataRow dr in datatable.Rows) { this._dt.ImportRow(dr); } } ReadDataTable(); } #endregion #region 读取数据 private void ReadDataTable() { try { DataTable tmpTable=_dt.Clone(); int first = this._pageNum * (this._pageIndex - 1); first = (first > 0) ? first : 0; if (this._dt.Rows.Count >= this._pageNum * this._pageIndex) { for (int i = first; i < this._pageNum * this._pageIndex; i++) { tmpTable.ImportRow(this._dt.Rows[i]); } } else { for (int i = first; i < this._dt.Rows.Count; i++) { tmpTable.ImportRow(this._dt.Rows[i]); } } this._dg.ItemsSource = tmpTable.DefaultView; tmpTable.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { DisplayPagingInfo(); } } #endregion #region 显示数据 private void DisplayPagingInfo() { if (this._pageIndex == 1) { this.BtnFirst.IsEnabled = false; this.BtnPrev.IsEnabled = false; } else { this.BtnFirst.IsEnabled = true; this.BtnPrev.IsEnabled = true; } if (this._pageIndex == this._maxIndex) { this.BtnNext.IsEnabled = false; this.BtnLast.IsEnabled = false; } else { this.BtnLast.IsEnabled = true; this.BtnNext.IsEnabled = true; } //this.txt_Record.Text = string.Format("每页{0}条/共{1}条", this.pageNum, this.totalNum); this.PageNumber.Text = this._pageNum.ToString(); this.TotalNumber.Text = this._totalNum.ToString(); this.PageIndexNumber.Text = this._pageIndex.ToString(); int first = (this._pageIndex - 4) > 0 ? (this._pageIndex - 4) : 1; int last = (first + 9) > this._maxIndex ? this._maxIndex : (first + 9); this.GridGrid.Children.Clear(); for (int i = first; i <= last; i++) { ColumnDefinition col = new ColumnDefinition(); this.GridGrid.ColumnDefinitions.Add(col); TextBlock tb = new TextBlock(); tb.Text = i.ToString(); //tb.Width = 40; tb.Style = FindResource("pageNumber") as Style; tb.MouseLeftButtonDown += new MouseButtonEventHandler(tb_MouseLeftButtonDown); tb.MouseLeftButtonUp += new MouseButtonEventHandler(tb_MouseLeftButtonUp); if (i == this._pageIndex) { tb.IsEnabled = false; } Grid.SetColumn(tb, this.GridGrid.ColumnDefinitions.Count - 1); Grid.SetRow(tb, 0); this.GridGrid.Children.Add(tb); } } void tb_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { TextBlock tb = sender as TextBlock; if (tb == null) { return; } int index = int.Parse(tb.Text.ToString()); this._pageIndex = index; if (index > this._maxIndex) { this._pageIndex = this._maxIndex; } if (index < 1) { this._pageIndex = 1; } ReadDataTable(); } void tb_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { e.Handled = true; } #endregion #region 首页 void btn_First_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { e.Handled = true; } void btn_First_Click(object sender, EventArgs e) { this._pageIndex = 1; ReadDataTable(); } #endregion #region 上一页 void btn_Prev_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { e.Handled = true; } void btn_Prev_Click(object sender, EventArgs e) { if (this._pageIndex <= 1) { return; } this._pageIndex--; ReadDataTable(); } #endregion #region 下一页 void btn_Next_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { e.Handled = true; } void btn_Next_Click(object sender, EventArgs e) { if (this._pageIndex >= this._maxIndex) { return; } this._pageIndex++; ReadDataTable(); } #endregion #region 末页 void btn_Last_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { e.Handled = true; } void btn_Last_Click(object sender, EventArgs e) { this._pageIndex = this._maxIndex; ReadDataTable(); } #endregion }}
3、调用:
界面前台引用: xmlns:local="clr-namespace:Client.UserControls"
分页控件显示: <local:DataPager x:Name="pagnav"></local:DataPager>
后台调用分页方法(调用WebApi接口):
Dictionary
using System;using System.Collections.Generic;using System.Configuration;using System.Data;using System.Linq;using System.Net.Http;using System.Net.Http.Formatting;using System.Text;using System.Threading.Tasks;using Ruang.Extend;namespace Client.Backend{ /// <summary> /// API调用基础类 /// </summary> public class ApiCaller { private static readonly string BaseUri = ConfigurationManager.AppSettings["ApiUri"]; /// <summary> /// GET请求--异步方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="action">方法</param> /// <param name="param">参数</param> /// <returns></returns> public static async Task<T> TryGetAsync<T>(string action, Dictionary<string, string> param) where T : class { using (HttpClient client = new HttpClient()) { //基地址/域名 client.BaseAddress = new Uri(BaseUri); //设定传输格式为json client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); StringBuilder strUri = new StringBuilder(); //方法 strUri.AppendFormat("{0}?", action); //参数 if (param.Count > 0) { foreach (KeyValuePair<string, string> pair in param) { strUri.AppendFormat("{0}={1}&&", pair.Key, pair.Value); } strUri.Remove(strUri.Length - 2, 2);//去掉'&&' } else { strUri.Remove(strUri.Length - 1, 1);//去掉'?' } HttpResponseMessage response = await client.GetAsync(strUri.ToString()); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); return JSONHelper.GetObjectFromJson<T>(result); } else { return null; } } } /// <summary> /// 无参数GET请求--异步方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="action"></param> /// <returns></returns> public static async Task<T> TryGetAsync<T>(string action) where T : class { using (HttpClient client = new HttpClient()) { //基地址/域名 client.BaseAddress = new Uri(BaseUri); //设定传输格式为json client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync(action); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); return JSONHelper.GetObjectFromJson<T>(result); } else { return null; } } } /// <summary> /// POST请求--异步方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="action">方法</param> /// <param name="param">参数</param> /// <returns></returns> public static async Task<T> TryPostAsync<T>(string action, object param) where T : class { using (HttpClient client = new HttpClient()) { //基地址/域名 client.BaseAddress = new Uri(BaseUri); //设定传输格式为json client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.PostAsync(action, param, new JsonMediaTypeFormatter()); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); return JSONHelper.GetObjectFromJson<T>(result); } else { return null; } } } /// <summary> /// GET请求--同步方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="action">方法</param> /// <param name="param">参数</param> /// <returns></returns> public static T TryGet<T>(string action, Dictionary<string, string> param) where T : class { using (HttpClient client = new HttpClient()) { //基地址/域名 client.BaseAddress = new Uri(BaseUri); //设定传输格式为json client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); StringBuilder strUri = new StringBuilder(); //方法 strUri.AppendFormat("{0}?", action); //参数 if (param.Count > 0) { foreach (KeyValuePair<string, string> pair in param) { strUri.AppendFormat("{0}={1}&&", pair.Key, pair.Value); } strUri.Remove(strUri.Length - 2, 2);//去掉'&&' } else { strUri.Remove(strUri.Length - 1, 1);//去掉'?' } HttpResponseMessage response = client.GetAsync(strUri.ToString()).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; return JSONHelper.GetObjectFromJson<T>(result); } else { return null; } } } /// <summary> /// POST请求--同步方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="action">方法</param> /// <param name="param">参数</param> /// <returns></returns> public static T TryPost<T>(string action, object param) where T : class { using (HttpClient client = new HttpClient()) { //基地址/域名 client.BaseAddress = new Uri(BaseUri); //设定传输格式为json client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PostAsync(action, param, new JsonMediaTypeFormatter()).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; return JSONHelper.GetObjectFromJson<T>(result); } else { return null; } } } }}
5、webapi分页接口类:
using RGang.BizLogic;using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;namespace API.Controllers{ /// <summary> /// 分页 /// </summary> public class PageController : ApiController { #region 分页 /// <summary> /// 分页 /// </summary> /// <param name="rolename">字段(逗号隔开)</param> /// <param name="pagesize">每页条数</param> /// <param name="currentpage">当前页数</param> /// <param name="tablename">表名</param> /// <param name="uniquefield">唯一标识</param> /// <param name="where">条件</param> /// <param name="orderby">排序</param> /// <returns></returns> [AcceptVerbs("GET")] public DataTable GetPage(string rolename, int pagesize, int currentpage, string tablename, string uniquefield, string where, string orderby) { // DBHelper.GetDataByPage("RowGuid",2,1, "INFO_MobileClient","RowGuid"," 1=1 ", " order by OperationDate desc"); int _totalnum; DataTable dt = DB.GetData_Page(rolename, pagesize, currentpage, tablename, uniquefield, where, orderby, out _totalnum); return dt; } #endregion }}
public static DataTable GetData_Page(string RoleName, int PageSize, int CurrPage, string TableName, string UniqueField, string Where, string OrderBy, out int TotalNum) { if (!Where.TrimStart(new char[0]).ToLower().StartsWith("where")) { Where = " where " + Where; } if (!(!(OrderBy.Trim() != "") || OrderBy.TrimStart(new char[0]).ToLower().StartsWith("order by"))) { OrderBy = " order By " + OrderBy; } DataTable table = null; Database database = DatabaseFactory.CreateDatabase(Conn.GetConnectionStringName("RongGuangMis_ConnectionString")); if (database.DbProviderFactory.ToString() == "System.Data.OracleClient.OracleClientFactory") { string str = "select " + RoleName + " from " + TableName + " " + Where + " " + OrderBy; string query = "select " + RoleName + " from ( select row_.*, rownum rownum_ from (" + str + ") row_ where rownum <= " + Convert.ToString((int)(CurrPage * PageSize)) + ") where rownum_ >" + Convert.ToString((int)((CurrPage - 1) * PageSize)); DbCommand sqlStringCommand = database.GetSqlStringCommand(query); table = database.ExecuteDataSet(sqlStringCommand).Tables[0]; string str3 = "select count(*) from " + TableName + " " + Where; sqlStringCommand = database.GetSqlStringCommand(str3); TotalNum = Convert.ToInt32(database.ExecuteScalar(sqlStringCommand)); return table; } DBOperate operate = new DBOperate(Conn.GetConnectionStringName()); return operate.GetData_Page(RoleName, PageSize, CurrPage, TableName, UniqueField, Where, OrderBy, out TotalNum); }
0 0
- WPF 自定义分页控件DataPager.xaml
- Silverlight分页控件 - DataPager
- datapager控件分页
- WPF自定义分页控件
- vs2008中分页控件DataPager
- ListView搭配DataPager控件实现分页--笔记
- silverlight分页控件DataPager使用要点
- 利用ListView和DataPager控件来对数据分页
- 使用Silverlight Toolkit的数据分页控件---DataPager
- .net3.5正统分页控件来了(ListView和DataPager)
- 使用Silverlight Toolkit的数据分页控件---DataPager
- 利用ListView和DataPager控件来对数据分页
- 利用ListView和DataPager控件来对数据分页
- WPF 控件模板 Simple Styles.xaml
- WPF 分页控件
- WPF分页控件
- wpf制作分页控件
- WPF DataGrid 分页自定义
- [RK3288][Android6.0] Ubuntu 编译环境错误小结
- javascript的面试要点
- YII2路由(Route)
- Android日历控件
- opencv 3.1.0在Ubuntu系统上编译 cannot find -lippicv错误
- WPF 自定义分页控件DataPager.xaml
- Server Tomcat v8.0 Server at localhost was unable to start within 45 seconds. If the server requires
- 13.5 常见Random类
- Path Sum III
- 通过Dockerfile 文件为linux images 添加新用户
- BLE蓝牙
- 数据库基础(面试常见题)
- kafka cluster
- java编程练习50题(含答案)