wpf研究之道——datagrid控件分页

这是我们的datagrid分页效果图,有上一页,下一页,可以跳到任何一页。当页码比较多的时候,只显示几页,其余用点点,界面实现如下:

 <!--分页-->
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top"  Grid.Row="2" Margin="0 20"  x:Name="fulltextPager">

            <Button x:Name="prePage" Click="prePage_Click" Style="{StaticResource btnPager}" ToolTip="上一页"/>

            <Button Style="{StaticResource btnPager}"  Content="1" 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="50" Height="25"></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 = 10;
        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 = 10, int pageIndex = 1)
        {
            this.PageSize = pageSize;
            this.DataSource = source;
            this.ItemCount = count;
            this.Total = this.ItemCount % PageSize == 0 ? ItemCount / PageSize : ItemCount / PageSize + 1;

            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 > 7)
            {
                //以当前页为分界点,向左借2个,向右借2个

                int leftLength = this.PageIndex - 1;
                int rightLength = this.Total - this.PageIndex;

                if (leftLength > 3 && rightLength > 3)
                {
                    this.PreVisible = Visibility.Visible;

                    for (int i = PageIndex - 2; i <= PageIndex + 2; i++)
                    {
                        this.Pages.Add(new Pages() { Name = i.ToString(), PageIndex = i });
                    }
                    this.NextVisible = Visibility.Visible;
                }

                if (rightLength <= 3)
                {
                    //右边的不够,向左边借
                    this.PreVisible = Visibility.Visible;

                    for (int i = this.PageIndex - (5 - rightLength); i <= this.Total - 1; i++)
                    {
                        this.Pages.Add(new Pages() { Name = i.ToString(), PageIndex = i });
                    }
                }
                if (leftLength <= 3)
                {
                    //左边的不够,向右边借
                    for (int i = 2; i <= this.PageIndex + (5 - leftLength); i++)
                    {
                        this.Pages.Add(new Pages() { Name = i.ToString(), PageIndex = i });
                    }
                    this.NextVisible = Visibility.Visible;
                }
            }
            else
            {
                for (int i = 2; i <= Total - 1; 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 < 1 || 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 - 1) * 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 = 1)
        {
            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 == 0 ? Visibility.Collapsed : Visibility.Visible;

            prePage.Content = "<<";
            btnGoLastPage.Visibility = Data.Total == 1 ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;

        }

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

FullTextList:数据源

itemCount:总数

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

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

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

原文地址:https://www.cnblogs.com/wangqiang3311/p/8744085.html

时间: 2024-08-05 22:59:13

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

.net MVC模式下easyui datagrid控件分页

此参照一位仁兄代码,稍作修改 视图代码: <div id="tab" class="easyui-tabs" data-options="tools:'#tab-tools'" style="width:800px;height:400px"> <div title="****" style="padding:0px;"> <div class="

WPF Grid布局 实现DataGrid控件宽充满布局

1.充满布局 显示设置DataGridTextColumn的属性Width="*" 实现DataGrid控件宽充满布局,代码与效果图片如下所示: 2.Header居中显示 WPF DataGrid属性中无DataGrid的Header居中显示属性,可在xaml代码中添加 设置风格代码 设置,代码如下: <!-- 设置Header居中 --> <DataGrid.ColumnHeaderStyle> <Style TargetType="DataG

WPF:获取DataGrid控件单元格DataGridCell

转载:http://blog.csdn.net/jhqin/article/details/7645357 /* ---------------------------------------------------------- 文件名称:DataGridPlus.cs 作者:秦建辉 MSN:[email protected] QQ:36748897 博客:http://blog.csdn.net/jhqin 开发环境: Visual Studio V2010 .NET Framework 4

wpf 中DataGrid 控件的样式设置及使用

本次要实现的效果为: 这个DataGrid需要绑定一个集合对象,所以要先定义一个Experience类,包含三个字段 /// <summary> /// 定义工作经历类 /// </summary> public class Experience { /// <summary> /// 获取或设置工作的起始时间 /// </summary> public string Start { get; set; } /// <summary> /// 获

easyUI的datagrid控件日期列不能正确显示Json格式数据的解决方案

EasyUI是一套比较轻巧易用的Jquery控件,在使用过程中遇到一个问题,它的列表控件——datagrid, 在显示日期列的时候,由于后台返回给页面的数据是Json格式的,其中的日期字段,在后台是正常的“2012-11-10 12:18:00”这样的格式,json序列化后返回到前台页面就被转换成一个像 /Date(1419264000000)/的格式,导致easyUI无法解析这个字段.经过一番研究,下面给出两种解决方式 希望能帮到大家! 第一种:比较简单 定义函数:function forma

.NET CORE(C#) WPF 方便的实现用户控件切换(祝大家新年快乐)

微信公众号:Dotnet9,网站:Dotnet9,问题或建议:请网站留言, 如果对您有所帮助:欢迎赞赏. .NET CORE(C#) WPF 方便的实现用户控件切换(祝大家新年快乐) 快到2020年了,祝大家新年快乐,今年2019最后一更,谢谢大家支持! 阅读导航 本文背景 代码实现 本文参考 源码 1. 本文背景 一个系统主界面,放上一个菜单,点击菜单在客户区切换不同的展示界面,这是很常规的设计,见下面展示效果图: 左侧一个菜单,点击菜单,右侧切换界面,界面切换动画使用MD控件的组件实现(自己

easyUI Datagrid 控件 param参数的用途探索

关于easyUI Datagrid  控件 param参数,官方文本很少解释,主要有如下说明: queryParams object When request remote data, sending additional parameters also. Code example: $('#dg').datagrid({ queryParams: { name: 'easyui', subject: 'datagrid' } }); 有人认为这个参数可有可无,比如: queryParams这个

AspNetPager控件分页使用方法

AspNetPager控件官方下载地址:http://www.webdiyer.com/aspnetpager/ 把控件加到项目中(添加自定义控件的方法),并把它拖放到页面上 <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="

基于MVC+EasyUI的Web开发框架经验总结(13)--DataGrid控件实现自动适应宽带高度

在默认情况下,EasyUI的DataGrid好像都没有具备自动宽度的适应功能,一般是指定像素宽度的,但是使用的人员计算机的屏幕分辨率可能不一样,因此导致有些地方显示太大或者太小,总是不能达到好的预期效果,如果DataGrid能够根据窗口尺寸进行伸缩,效果应该好很多.本文主要介绍DataGrid控件实现自动适应宽带高度的操作. 首先我们需要定义一个resizeDataGrid的扩展函数,方便在页面里面进行调用,扩展函数定义如下所示. //datagrid宽度高度自动调整的函数 $.fn.exten