wpf分页控件(代码片段)

xwzlovecshap xwzlovecshap     2022-12-07     575

关键词:

最近要写个程序要用到分页控件,找到了很多好高级的,代码拿到了也看不懂。最后找到了一个能看懂的,完善了一下。

源控件https://www.cnblogs.com/madehua/archive/2011/12/14/2287672.html 

 

页面代码

技术图片
<UserControl x:Class="WpfCustomControlLibrary.PagerControl"
             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" 
             xmlns:local="clr-namespace:WpfCustomControlLibrary"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid x:Name="MainGrid">
        <Grid.Resources>
            <Style x:Key="ButtonStyleOne" TargetType="Button">
                <Setter Property="Margin" Value="5"/>
                <Setter Property="Background" Value="CadetBlue"/>
                <Setter Property="VerticalAlignment" Value="Center"/>
                <Setter Property="Width" Value="55"/>
                <Setter Property="VerticalAlignment" Value="Center"/>
                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="True">
                        <Setter Property="Background" Value="CadetBlue"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Background" Value="Red"/>
                    </Trigger>
                </Style.Triggers>
               
            </Style>

            <Style x:Key="ButtonTwo" TargetType="Button">
                <Setter Property="BorderBrush" Value="x:Null"/>
                <Setter Property="Background" Value="White"/>
                <Setter Property="Width" Value="30"/>
                <Setter Property="Height" Value="20"/>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="Azure"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
            
        </Grid.Resources>
        <StackPanel Orientation="Horizontal" Background="White">

            <Button Name="FirstButton" Content="首页" Style="StaticResource  ButtonStyleOne" Click="FirstButton_Click" />
           

            <Button Name="PreButton" Content="上一页" Style="StaticResource  ButtonStyleOne" Click="PreButton_Click" />
            <StackPanel x:Name="ButtonPages" Orientation="Horizontal" Background="White">
              
            </StackPanel>
           

            <Button Name="NextButton" Content="下一页" Style="StaticResource  ButtonStyleOne" Click="NextButton_Click" />
            <Button Name="LastButton" Content="尾页" Style="StaticResource  ButtonStyleOne" Click="LastButton_Click" />

            <TextBlock VerticalAlignment="Center" FontSize="12" > 
                <TextBlock Text="【共"/>
                <TextBlock Name="txtCount" Text="" Foreground="Red"/>
                <TextBlock Text="页】"/> 
                <TextBlock Text="【当前第"/>
                <TextBlock Name="txtCurrent" Foreground="Red"/>
                <TextBlock Text="页】"/>
                 <TextBlock Text="【共"/>
                <TextBlock Name="txtAll" Foreground="Red"/>
                <TextBlock Text="条记录】"/>
            </TextBlock>

        </StackPanel>
    </Grid>
</UserControl>
View Code

后台代码

技术图片
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

using System.Windows.Media;

namespace WpfCustomControlLibrary

    //public delegate void PagerIndexChangingEvent(int pageIndex, EventArgs e);

    /// <summary>
    /// PagerControl.xaml 的交互逻辑
    /// </summary>
    public partial class PagerControl : UserControl
    
        public PagerControl()
        
            InitializeComponent();
        
        //public event PagerIndexChangingEvent PageIndexChanging;

        /// <summary>
        /// 当前页索引
        /// </summary>
        private int pageIndex = 0;

        public int PageIndex
        
            get  return pageIndex; 
            set  pageIndex = value; 
        
        /// <summary>
        /// 总页数
        /// </summary>
        private int pageCount;
        /// <summary>
        /// 一页个数
        /// </summary>
        private int pageSize = 12;

        public int PageSize
        
            get  return pageSize; 
            set  pageSize = value; 
        

        public IList Logs  get; set; //数据源
        public DataGrid dg  get; set; //装载数据的DateGrid

        //数据个数

        private int count;
   
        public int Count
        
            get  return count; 
            set
            
                count = value;
                if (count == 0)
                    pageCount = 0;// ButtonPages.Children.Count+ 
                else
                    pageCount =  count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
                txtCount.Text = pageCount.ToString();
                txtAll.Text = count.ToString();

             
                if (pageCount<=5&& pageCount> ButtonPages.Children.Count)
                

                    Button button = new Button();
                    Style myStyle = (Style)MainGrid.FindResource("ButtonTwo");//TabItemStyle 这个样式是引用的资源文件中的样式名称
                    button.Style = myStyle;
                    button.Click += ButtonTwo_Click;

                    button.Content = (ButtonPages.Children.Count + 1).ToString();
                    if (ButtonPages.Children.Count == 0) button.Background = Brushes.LightBlue;
                    ButtonPages.Children.Add(button);
                
               
               
                Init(null);
            
        

        public void Init(EventArgs e)
        
            try
            
                InitButton();
                int temp = pageIndex + 1;
                if (pageCount == 0)
                    txtCurrent.Text = "0";
                else
                    txtCurrent.Text = temp.ToString();
                if (e != null)
                
                    //PageIndexChanging(pageIndex, e);
                    ChangeGridPage(Logs,dg);
                
            
            catch (Exception ex)
            
                MessageBox.Show(ex.ToString());
            
        

     public   void InitButton()
        
            this.FirstButton.IsEnabled = true;
            this.PreButton.IsEnabled = true;
            this.NextButton.IsEnabled = true;
            this.LastButton.IsEnabled = true;
            //this.FirstButton.Background = Brushes.CadetBlue;
            //this.PreButton.Background = Brushes.CadetBlue;
            //this.NextButton.Background = Brushes.CadetBlue;
            //this.LastButton.Background = Brushes.CadetBlue;

            //总共一页
            if (pageCount < 2)
            
                //this.FirstButton.Background = Brushes.Red;
                //this.PreButton.Background = Brushes.Red;
                //this.NextButton.Background = Brushes.Red;
                //this.LastButton.Background = Brushes.Red;
                this.FirstButton.IsEnabled = false;
                this.PreButton.IsEnabled = false;
                this.NextButton.IsEnabled = false;
                this.LastButton.IsEnabled = false;

                return;
            

            //第一页
            if (pageIndex == 0)
            
                //this.FirstButton.Background = Brushes.Ivory;
                //this.PreButton.Background = Brushes.Ivory;
                this.FirstButton.IsEnabled = false;
                this.PreButton.IsEnabled = false;

                return;
            

            //最后一页
            if (pageIndex + 1 == pageCount)
            
                //this.NextButton.Background = Brushes.Ivory;
                //this.LastButton.Background = Brushes.Ivory;
                this.NextButton.IsEnabled = false;
                this.LastButton.IsEnabled = false;

            
        

       
        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FirstButton_Click(object sender, RoutedEventArgs e)
        
            if (count == 0) return;
            pageIndex = 0;
            for (int i = 0; i < 5; i++)
            
                (ButtonPages.Children[i] as Button).Background = Brushes.White;
                (ButtonPages.Children[i] as Button).Content = i + 1;
                if (i == pageIndex)
                
                    (ButtonPages.Children[i] as Button).Background = Brushes.LightBlue;
                

            
            Init(e);
        

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PreButton_Click(object sender, RoutedEventArgs e)
        
            if (pageIndex == 0) return;
            --pageIndex;
            AddAndRemove(pageIndex, sender,e);
            Init(e);
        

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NextButton_Click(object sender, RoutedEventArgs e)
        
            if (pageIndex >=count) return;
            ++pageIndex;
            AddAndRemove(pageIndex, sender, e);
            Init(e);
        

        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LastButton_Click(object sender, RoutedEventArgs e)
        
            if (count <= 0) return;
            pageIndex = pageCount - 1;
            for (int i = 0; i < 5; i++)
            
                (ButtonPages.Children[i] as Button).Background = Brushes.White;
                (ButtonPages.Children[i] as Button).Content = pageCount - 5 + i + 1;
                if (pageCount - 5 + i == pageIndex)
                
                    (ButtonPages.Children[i] as Button).Background = Brushes.LightBlue;
                

            
            Init(e);
        

        private void Button_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        
            if (!(sender as Button).IsEnabled)
            
                (sender as Button).Background = Brushes.Red;
            
            else
            
                (sender as Button).Background = Brushes.CadetBlue;
            

        
        private void ButtonTwo_Click(object sender ,RoutedEventArgs e)
        


            pageIndex = int.Parse((sender as Button).Content.ToString())-1;

            if ((pageCount <= 5 || pageIndex <= 2 || pageIndex >= pageCount - 3) && (int.Parse((ButtonPages.Children[0] as Button).Content.ToString()) == 1 || int.Parse((ButtonPages.Children[4] as Button).Content.ToString()) == pageCount))
            
                for (int i = 0; i < ButtonPages.Children.Count; i++)
                
                    (ButtonPages.Children[i] as Button).Background = Brushes.White;
                    if ((ButtonPages.Children[i] as Button).Content.ToString() == (pageIndex + 1).ToString())
                    
                        (ButtonPages.Children[i] as Button).Background = Brushes.LightBlue;
                    

                


            
            else
            
                int Firstindex = pageIndex - 2;
                if (Firstindex + 5 > pageCount)
                
                    Firstindex = pageCount - 5;


                
                for (int i = 0; i < 5;)
                
                    (ButtonPages.Children[i] as Button).Background = Brushes.White;
                    if (Firstindex + 1 <= 0)
                    
                        Firstindex++;
                        continue;
                    
                    

                    (ButtonPages.Children[i] as Button).Content = Firstindex + 1;
                    if (Firstindex == pageIndex)
                    
                        (ButtonPages.Children[i] as Button).Background = Brushes.LightBlue;
                    
                    Firstindex++;
                    i++;
                
            

            Init(e);

        

        private void AddAndRemove(int Index,object sender,  RoutedEventArgs e)
        
            pageIndex = Index;

            if ((pageCount <= 5 || pageIndex <= 2 || pageIndex >= pageCount - 3)&& (int.Parse((ButtonPages.Children[0] as Button).Content.ToString()) == 1 || int.Parse((ButtonPages.Children[4] as Button).Content.ToString()) == pageCount))
            
                for (int i = 0; i < ButtonPages.Children.Count; i++)
                
                    (ButtonPages.Children[i] as Button).Background = Brushes.White;
                    if ((ButtonPages.Children[i] as Button).Content.ToString() == (pageIndex + 1).ToString())
                    
                        (ButtonPages.Children[i] as Button).Background = Brushes.LightBlue;
                    

                


            
            else
            
                int Firstindex = pageIndex - 2;
                for (int i = 0; i < 5; i++)
                
                    (ButtonPages.Children[i] as Button).Background = Brushes.White;
                    (ButtonPages.Children[i] as Button).Content = Firstindex + 1;
                    if (Firstindex == pageIndex)
                    
                        (ButtonPages.Children[i] as Button).Background = Brushes.LightBlue;
                    
                    Firstindex++;
                
            

            Init(e);
        

       
        private void ChangeGridPage(IList AllLog,DataGrid datagrid)
        
          
            Count = AllLog.Count;//设置总数据量
            datagrid.Items.Clear();//清空当前数据

            int number =PageSize;
            if (AllLog.Count - PageSize * pageIndex < PageSize)
            
                //获取当前页数据量,最后一页数据量不满
                number = AllLog.Count - PageSize * pageIndex;
            

            for (int i = PageSize * pageIndex; i < PageSize * pageIndex+number; i++)
            
                datagrid.Items.Add(AllLog[i]);//添加数据
            


            //foreach (var item in AllLog.GetRange(PageSize * pageIndex, number))
            //
            //    datagrid.Items.Add(item);//添加数据
            //
        

       


    
View Code

调用页面代码

 xmlns:MyNamespace="clr-namespace:WpfCustomControlLibrary;assembly=WpfCustomControlLibrary"
 //先引用自定义控件项目

  <MyNamespace:PagerControl HorizontalAlignment="Right" x:Name="pager" Grid.Row="3">
            
        </MyNamespace:PagerControl>   

调用页面后台代码

public MainForm()
        
           
            InitializeComponent();
           
            pager.PageSize = 30;//设置每页数据量
            pager.Logs = AllLog;//设置数据源IList格式,DataTable尝试传DataTable.Rows,不行就把控件后台代码重写了吧
            pager.dg = datagrid;//装载数据的DataGrid控件
           

        

 

有些问题没有处理,不知为何控件IsEnable属性设置为空时,无法改变按钮的颜色。

跳转没做,因为我的项目总共的数据量也不大,需要的自己加上,只要把Index传给 AddAndRemove(int Index,object sender,  RoutedEventArgs e) 这个方法就好了,

因为这个方法我是嵌在事件里用的,实际只传Index就可以,其余两个属性照搬事件的属性就好。

 

wpf管理系统自定义分页控件-wpf特工队内部资料(代码片段)

原文:WPF管理系统自定义分页控件-WPF特工队内部资料  最近做一个演示的管理系统项目,需要用到分页控件,在网上找了很多,依然找到与UI模版匹配的,最后干脆自己写一个。  分页控件分析:    1、分页控件分简单... 查看详情

wpf实现datagrid/listview分页控件(转)(代码片段)

...,而且用户体验也很糟糕。这篇博客将介绍如何创建一个分页控件。为了简单起见,这个分页控件目前只有首页/上一页/下一页/末页/总页数/第几页等功能。实现思路,首页/上一页/下一页/末页这四个通过路由事件来实现,在 查看详情

wpf实现datagrid/listview分页控件(转)(代码片段)

...,而且用户体验也很糟糕。这篇博客将介绍如何创建一个分页控件。为了简单起见,这个分页控件目前只有首页/上一页/下一页/末页/总页数/第几页等功能。实现思路,首页/上一页/下一页/末页这四个通过路由事件来实现,在 查看详情

2021-11-07wpf上位机78-智能停车场项目专题-分页控件的封装(代码片段)

PaginationModelpublicclassPaginationModel:BindableBase#region构造函数publicPaginationModel() 查看详情

wpf控件(代码片段)

内容控件:这些控件可包含嵌套元素,比如Label,Button,ToolTip,ScrollViewer带有标题的内容控件:允许添加主要内容部分以及单独标题部分的内容控件,比如TabItem,GroupBox,Expanderl文本控件:允许输入文本,支持Textbox,PasswordBox,... 查看详情

wpf自定义控件(代码片段)

原文:WPF自定义控件封装了一个选择年月的控件,XAML代码:<UserControlx:Class="SunCreate.CombatPlatform.Client.DateMonthPicker"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsof 查看详情

wpf中动态创建和删除控件(代码片段)

原文:WPF中动态创建和删除控件 动态创建控件1.容器控件.RegisterName("Name",要注册的控件)?//注册控件2.容器控件.FindName("Name")as?控件类型??????//找到控件并转换成相应类型注意:仅通过控件.Name来设置是不能通过FindName来找... 查看详情

wpf动画显示控件(代码片段)

原文:WPF动画显示控件  当我们要显示一个控件的时候,不仅仅要显示这个控件,还要有动画的效果。  主要用到了DoubleAnimation类。publicstaticvoidShowAnimation(objectcontrol)Typetype=control.GetType();switch(type.Name)case"Border":Bord 查看详情

如何实现wpf代码查看器控件(代码片段)

 如何实现WPF代码查看器控件CodeViewer作者:WPFDevelopersOrg-驚鏵原文链接[1]:https://github.com/WPFDevelopersOrg/WPFDevelopers框架使用.NET40;VisualStudio2019;代码展示需要使用到AvalonEdit是基于WPF的代码显示控件,项目地址[2] 查看详情

wpf自定义控件の自定义控件(代码片段)

原文:WPF自定义控件(四)の自定义控件在实际工作中,WPF提供的控件并不能完全满足不同的设计需求。这时,需要我们设计自定义控件。这里LZ总结一些自己的思路,特性如下:CouplingUITemplateBehaviourFunctionPackage下面举例说说在项... 查看详情

wpf实现步骤控件(代码片段)

 WPF实现步骤控件控件名:Step作 者:WPFDevelopersOrg-驚鏵原文链接[1]:https://github.com/WPFDevelopersOrg/WPFDevelopers框架使用.NET40;VisualStudio2019;Step继承ItemsControl使用Grid嵌套ProgressBar和ItemsPre 查看详情

wpf查找控件的所有子控件(代码片段)

///<summary>///查找子控件///</summary>///<typeparamname="T">控件类型</typeparam>///<paramname="parent">父控件依赖对象</param>///<paramname="lstT">子控件列表</param>publicsta 查看详情

wpf实现炫酷loading控件(代码片段)

原文:WPF实现炫酷Loading控件Win8系统的Loading效果还是很不错的,网上也有人用CSS3等技术实现,研究了一下,并打算用WPF自定义一个Loading控件实现类似的效果,并可以让用户对Loading的颗粒(Particle)背景颜色进行自定义,话不多说... 查看详情

wpf自定义控件の重写原生控件样式模板(代码片段)

原文:WPF自定义控件(二)の重写原生控件样式模板    话外篇: 要写一个圆形控件,用Clip,重写模板,去除样式引用圆形图片可以有这三种方式。  开发过程中,我们有时候用WPF原生的控件就能实现自己的... 查看详情

wpf控件拖动(代码片段)

Thumb拖动上代码!1<Windowx:Class="Thumb控件移动.MainWindow"2xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"4xmlns:d="http://schemas.mi 查看详情

wpf中窗口控件的跨线程调用(代码片段)

原文:WPF中窗口控件的跨线程调用在WinForm中,我们要跨线程访问窗口控件,只需要设置属性CheckForIllegalCrossThreadCalls=false;即可。在WPF中要麻烦一下,同样的不允许跨线程访问,因为没有权限,访问了会抛异常;没有CheckForIllegalCross... 查看详情

wpf自定义控件の扩展控件(代码片段)

原文:WPF自定义控件(三)の扩展控件    扩展控件,顾名思义就是对已有的控件进行扩展,一般继承于已有的原生控件,不排除继承于自定义的控件,不过这样做意义不大,因为既然都自定义了,为什么不一步到... 查看详情

[wpf自定义控件]从contentcontrol开始入门自定义控件(代码片段)

原文:[WPF自定义控件]从ContentControl开始入门自定义控件1.前言我去年写过一个在UWP自定义控件的系列博客,大部分的经验都可以用在WPF中(只有一点小区别)。这篇文章的目的是快速入门自定义控件的开发,所以尽量精简了篇幅... 查看详情