1. 程式人生 > 實用技巧 >WPF分頁控制元件

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就可以,其餘兩個屬性照搬事件的屬性就好。