WPF分页控件

Posted xwzlovecshap

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF分页控件相关的知识,希望对你有一定的参考价值。

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

源控件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特工队内部资料

WPF 之列表分页控件

WPF 实现 DataGrid/ListView 分页控件

WPF 实现 DataGrid/ListView 分页控件(转)

WPF 实现 DataGrid/ListView 分页控件(转)