WPF 分页控件的简单实现

想做个分页控件,想了想逻辑实现太复杂了,这不,用奇怪的方式实现了它,

看看效果:

image

下面就粘代码:

新建一个Pagination类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPFDemos
{
    public class Pagination : Control
    {
        private Button _btnPrev = null;
        private Button _btnOne = null;
        private Button _btnDotPrev = null;
        private Button _btnCenterOne = null;
        private Button _btnCenterTwo = null;
        private Button _btnCenterThree = null;
        private Button _btnCenterFour = null;
        private Button _btnCenterFive = null;
        private Button _btnDotNext = null;
        private Button _btnLast = null;
        private Button _btnNext = null;
        public int PageCount
        {
            get { return (int)GetValue(PageCountProperty); }
            set { SetValue(PageCountProperty, value); }
        }
        public static readonly DependencyProperty PageCountProperty =
            DependencyProperty.Register("PageCount", typeof(int), typeof(Pagination), new PropertyMetadata(1, (d, e) =>
            {
                if (!(d is Pagination pagination)) return;
                var page = (int)e.NewValue;
                pagination.IsSimple = page < 6;
            }));
        public bool IsSimple
        {
            get { return (bool)GetValue(IsSimpleProperty); }
            set { SetValue(IsSimpleProperty, value); }
        }
        public static readonly DependencyProperty IsSimpleProperty =
            DependencyProperty.Register("IsSimple", typeof(bool), typeof(Pagination), new PropertyMetadata(false));

        public int CurrentPage
        {
            get { return (int)GetValue(CurrentPageProperty); }
            set { SetValue(CurrentPageProperty, value); }
        }
        public static readonly DependencyProperty CurrentPageProperty =
            DependencyProperty.Register("CurrentPage", typeof(int), typeof(Pagination), new PropertyMetadata(1, (d, e) =>
            {
                if (!(d is Pagination pagination)) return;
                if (pagination.PageCount > 5)
                {
                    pagination.UpdateControl();
                }
                else
                {
                    pagination.UpdateControlSimple();
                }
                RoutedEventArgs args = new RoutedEventArgs()
                {
                    RoutedEvent = IndexChangedEvent,
                    Source = pagination,
                };
                pagination.RaiseEvent(args);
            }));

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (PageCount > 5)
            {
                InitControls();
            }
            else
            {
                InitControlsSimple();
            }
        }
        private List<Button> _simpleButtons = new List<Button>();
        private void InitControlsSimple()
        {
            _btnPrev = GetTemplateChild("btnPrev") as Button;
            _btnCenterOne = GetTemplateChild("btnCenterOne") as Button;
            _btnCenterTwo = GetTemplateChild("btnCenterTwo") as Button;
            _btnCenterThree = GetTemplateChild("btnCenterThree") as Button;
            _btnCenterFour = GetTemplateChild("btnCenterFour") as Button;
            _btnCenterFive = GetTemplateChild("btnCenterFive") as Button;
            _btnNext = GetTemplateChild("btnNext") as Button;
            _simpleButtons.Clear();
            _simpleButtons.Add(_btnCenterOne);
            _simpleButtons.Add(_btnCenterTwo);
            _simpleButtons.Add(_btnCenterThree);
            _simpleButtons.Add(_btnCenterFour);
            _simpleButtons.Add(_btnCenterFive);
            BindClickSimple();
            UpdateControlSimple();
        }
        public static readonly RoutedEvent IndexChangedEvent = EventManager.RegisterRoutedEvent("IndexChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Pagination));
        //CLR事件包装
        public event RoutedEventHandler IndexChanged
        {
            add { this.AddHandler(IndexChangedEvent, value); }
            remove { this.RemoveHandler(IndexChangedEvent, value); }
        }

        private void UpdateControlSimple()
        {
            _btnCenterOne.Visibility = PageCount >= 1 ? Visibility.Visible : Visibility.Collapsed;
            _btnCenterTwo.Visibility = PageCount >= 2 ? Visibility.Visible : Visibility.Collapsed;
            _btnCenterThree.Visibility = PageCount >= 3 ? Visibility.Visible : Visibility.Collapsed;
            _btnCenterFour.Visibility = PageCount >= 4 ? Visibility.Visible : Visibility.Collapsed;
            _btnCenterFive.Visibility = PageCount >= 5 ? Visibility.Visible : Visibility.Collapsed;
            _btnPrev.IsEnabled = CurrentPage > 1;
            _btnNext.IsEnabled = CurrentPage < PageCount;
            _btnCenterOne.Background = _btnCenterTwo.Background = _btnCenterThree.Background = _btnCenterFour.Background = _btnCenterFive.Background = Brushes.LightBlue;
            _simpleButtons[CurrentPage - 1].Background = Brushes.Green;
        }

        private void BindClickSimple()
        {
            _btnPrev.Click += (s, e) => CurrentPage -= 1;
            _btnCenterOne.Click += (s, e) => CurrentPage = 1;
            _btnCenterTwo.Click += (s, e) => CurrentPage = 2;
            _btnCenterThree.Click += (s, e) => CurrentPage = 3;
            _btnCenterFour.Click += (s, e) => CurrentPage = 4;
            _btnCenterFive.Click += (s, e) => CurrentPage = 5;
            _btnNext.Click += (s, e) => CurrentPage += 1;
        }

        private void InitControls()
        {
            _btnPrev = GetTemplateChild("btnPrev") as Button;
            _btnOne = GetTemplateChild("btnOne") as Button;
            _btnDotPrev = GetTemplateChild("btnDotPrev") as Button;
            _btnCenterOne = GetTemplateChild("btnCenterOne") as Button;
            _btnCenterTwo = GetTemplateChild("btnCenterTwo") as Button;
            _btnCenterThree = GetTemplateChild("btnCenterThree") as Button;
            _btnCenterFour = GetTemplateChild("btnCenterFour") as Button;
            _btnCenterFive = GetTemplateChild("btnCenterFive") as Button;
            _btnDotNext = GetTemplateChild("btnDotNext") as Button;
            _btnLast = GetTemplateChild("btnLast") as Button;
            _btnNext = GetTemplateChild("btnNext") as Button;
            BindClick();
            UpdateControl();
        }
        private void BindClick()
        {
            _btnPrev.Click += (s, e) => SetIndex(-1);
            _btnOne.Click += (s, e) => SetIndex(1 - CurrentPage);
            _btnDotPrev.Click += (s, e) => SetIndex(-3);
            _btnCenterOne.Click += (s, e) => SetIndex(-2);
            _btnCenterTwo.Click += (s, e) => SetIndex(-1);
            _btnCenterFour.Click += (s, e) => SetIndex(1);
            _btnCenterFive.Click += (s, e) => SetIndex(2);
            _btnDotNext.Click += (s, e) => SetIndex(3);
            _btnLast.Click += (s, e) => SetIndex(PageCount - CurrentPage);
            _btnNext.Click += (s, e) => SetIndex(1);
        }
        public void SetIndex(int page)
        {
            if (page < 0)
            {
                if (CurrentPage + page > 0)
                {
                    CurrentPage += page;
                }
            }
            else if (page > 0)
            {
                if (CurrentPage + page <= PageCount)
                {
                    CurrentPage += page;
                }
            }
        }

        private void UpdateControl()
        {
            _btnPrev.IsEnabled = CurrentPage > 1;
            _btnOne.Visibility = CurrentPage < 4 ? Visibility.Collapsed : Visibility.Visible;
            _btnDotPrev.Visibility = CurrentPage < 4 ? Visibility.Collapsed : Visibility.Visible;
            _btnCenterOne.Visibility = CurrentPage != 3 && CurrentPage != PageCount ? Visibility.Collapsed : Visibility.Visible;
            _btnCenterTwo.Visibility = CurrentPage == 1 || (PageCount - CurrentPage) == 2 ? Visibility.Collapsed : Visibility.Visible;
            _btnCenterFour.Visibility = CurrentPage == 3 || CurrentPage == PageCount ? Visibility.Collapsed : Visibility.Visible;
            _btnCenterFive.Visibility = CurrentPage != 1 && (PageCount - CurrentPage) != 2 ? Visibility.Collapsed : Visibility.Visible;
            _btnDotNext.Visibility = PageCount - CurrentPage < 3 ? Visibility.Collapsed : Visibility.Visible;
            _btnLast.Visibility = PageCount - CurrentPage < 3 ? Visibility.Collapsed : Visibility.Visible;
            _btnNext.IsEnabled = CurrentPage != PageCount;

            _btnOne.Content = 1;
            _btnCenterOne.Content = CurrentPage - 2;
            _btnCenterTwo.Content = CurrentPage - 1;
            _btnCenterThree.Content = CurrentPage;
            _btnCenterFour.Content = CurrentPage + 1;
            _btnCenterFive.Content = CurrentPage + 2;
            _btnLast.Content = PageCount;
        }
    }
}

在App.xaml内新增样式:

<Style x:Key="PageBtn" TargetType="Button">
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="MinWidth" Value="35"/>
        <Setter Property="Margin" Value="3 0"/>
        <Setter Property="Padding" Value="0"/>
        <Setter Property="Background" Value="LightBlue"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border x:Name="border" CornerRadius="6" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True" SourceName="border">
                            <Setter Property="Background" Value="Red" TargetName="border"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Background" Value="Gray" TargetName="border"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="PageCurrent" TargetType="Button">
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="MinWidth" Value="35"/>
        <Setter Property="Margin" Value="3 0"/>
        <Setter Property="Padding" Value="0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border x:Name="border" CornerRadius="6" Background="Green">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style TargetType="local:Pagination">
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:Pagination">
                    <StackPanel Orientation="Horizontal">
                        <Button Style="{StaticResource PageBtn}" x:Name="btnPrev" Content="上一页"></Button>
                        <Button Style="{StaticResource PageBtn}" x:Name="btnOne" Content="1"></Button>
                        <Button Style="{StaticResource PageBtn}" x:Name="btnDotPrev" Content="..."></Button>
                        <Button Style="{StaticResource PageBtn}" x:Name="btnCenterOne" Content="1"></Button>
                        <Button Style="{StaticResource PageBtn}" x:Name="btnCenterTwo" Content="2"></Button>
                        <Button Style="{StaticResource PageCurrent}" x:Name="btnCenterThree" Content="3"></Button>
                        <Button Style="{StaticResource PageBtn}" x:Name="btnCenterFour" Content="4"></Button>
                        <Button Style="{StaticResource PageBtn}" x:Name="btnCenterFive" Content="5"></Button>
                        <Button Style="{StaticResource PageBtn}" x:Name="btnDotNext" Content="..."></Button>
                        <Button Style="{StaticResource PageBtn}" x:Name="btnLast" Content="5"></Button>
                        <Button Style="{StaticResource PageBtn}" x:Name="btnNext" Content="下一页"></Button>
                    </StackPanel>
                   
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsSimple" Value="True">
                <Setter Property="Template" >
                    <Setter.Value>
                        <ControlTemplate TargetType="local:Pagination">
                            <StackPanel Orientation="Horizontal">
                                <Button Style="{StaticResource PageBtn}" x:Name="btnPrev" Content="上一页"></Button>
                                <Button Style="{StaticResource PageBtn}" x:Name="btnCenterOne" Content="1"></Button>
                                <Button Style="{StaticResource PageBtn}" x:Name="btnCenterTwo" Content="2"></Button>
                                <Button Style="{StaticResource PageBtn}" x:Name="btnCenterThree" Content="3"></Button>
                                <Button Style="{StaticResource PageBtn}" x:Name="btnCenterFour" Content="4"></Button>
                                <Button Style="{StaticResource PageBtn}" x:Name="btnCenterFive" Content="5"></Button>
                                <Button Style="{StaticResource PageBtn}" x:Name="btnNext" Content="下一页"></Button>
                            </StackPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                        </Trigger>
        </Style.Triggers>
    </Style>

MainWindow测试代码如下:

<Window x:Class="WPFDemos.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFDemos"
        mc:Ignorable="d"
        x:Name="widnow"
        WindowStartupLocation="CenterScreen"
        UseLayoutRounding="True"
        Background="#F5F5F5"
        FontSize="16"
        Title="分页" Height="500" Width="1000">
    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <local:Pagination x:Name="pag0" PageCount="3" Height="35" HorizontalAlignment="Center"/>
            <TextBlock Margin="10" HorizontalAlignment="Center">
                <Run Text="当前页:"/>
                <Run Text="{Binding CurrentPage,ElementName=pag0}"/>
            </TextBlock>
            
            <local:Pagination x:Name="pag" PageCount="5" Height="35" HorizontalAlignment="Center"/>
            <TextBlock Margin="10" HorizontalAlignment="Center">
                <Run Text="当前页:"/>
                <Run Text="{Binding CurrentPage,ElementName=pag}"/>
            </TextBlock>
            
            <local:Pagination x:Name="pag1" PageCount="35" Height="35" IndexChanged="pag1_IndexChanged"/>
            <TextBlock Margin="10" HorizontalAlignment="Center">
                <Run Text="当前页:"/>
                <Run Text="{Binding CurrentPage,ElementName=pag1}"/>
            </TextBlock>
        </StackPanel>
        
    </Grid>
</Window>

ok,结束

© 版权声明
THE END
喜欢就支持一下吧
点赞17 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情

    暂无评论内容