WPF自定义翻页控件

XAML文件如下:

XML 复制代码
<UserControl
    x:Class="CTMVVMDemo.View.UserControls.DataPager"
    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:local="clr-namespace:CTMVVMDemo.View.UserControls"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Name="userControl"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">
    <Grid>
        <!--
            一个视图数据源一般情况来自两处:
            1。ViewModel
            2。.cs文件
        -->

        <StackPanel
            HorizontalAlignment="Right"
            VerticalAlignment="Center"
            Orientation="Horizontal">
            <TextBlock Text="共" />
            <TextBlock Margin="4,0" Text="{Binding TotalCount, ElementName=userControl}" />
            <TextBlock Text="条记录,每页" />
            <ComboBox
                Grid.Column="0"
                Width="60"
                Height="24"
                Margin="5,0,0,0"
                Padding="0"
                VerticalAlignment="Center"
                HorizontalContentAlignment="Center"
                VerticalContentAlignment="Center"
                Cursor="Hand"
                ItemsSource="{Binding ElementName=userControl, Path=PageSizes}"
                SelectedItem="{Binding PageSize, ElementName=userControl}" />
            <TextBlock Text="条,第" />
            <TextBlock Margin="4,0,2,0" Text="{Binding PageIndex, ElementName=userControl}" />
            <TextBlock Text="/" />
            <TextBlock Margin="2,0,4,0" Text="{Binding PageCount, ElementName=userControl}" />
            <TextBlock Text="页" />
            <Button
                x:Name="btnFirst"
                Margin="10,0,0,0"
                VerticalAlignment="Center"
                Click="btnFirst_Click"
                Content="首页"
                FontSize="14"
                IsEnabled="{Binding CanGoFirstOrPrev, ElementName=userControl}" />
            <Button
                x:Name="btnPrev"
                Margin="10,0,0,0"
                VerticalAlignment="Center"
                Click="btnPrev_Click"
                Content="上一页"
                FontSize="14"
                IsEnabled="{Binding CanGoFirstOrPrev, ElementName=userControl}" />
            <Button
                x:Name="btnNext"
                Margin="10,0,10,0"
                VerticalAlignment="Center"
                Click="btnNext_Click"
                Content="下一页"
                FontSize="14"
                IsEnabled="{Binding CanGoLastOrNext, ElementName=userControl}" />

            <Button
                x:Name="btnLast"
                Margin="10,0,10,0"
                VerticalAlignment="Center"
                Click="btnLast_Click"
                Content="末页"
                FontSize="14"
                IsEnabled="{Binding CanGoLastOrNext, ElementName=userControl}" />
        </StackPanel>

    </Grid>
</UserControl>

依赖属性的代码如下:

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace CTMVVMDemo.View.UserControls
{
    public partial class DataPager : UserControl, INotifyPropertyChanged
    {
        public DataPager()
        {
            InitializeComponent();
        }

        #region 路由事件
        public static readonly RoutedEvent PageChangedEvent = EventManager.RegisterRoutedEvent(
            "PageChanged",
            RoutingStrategy.Bubble,
            typeof(RoutedEventHandler),
            typeof(DataPager));

        public event RoutedEventHandler PageChanged
        {
            add { AddHandler(PageChangedEvent, value); }
            remove { RemoveHandler(PageChangedEvent, value); }
        }
        #endregion

        #region 依赖属性

        /// <summary>
        /// 当前页
        /// </summary>
        public int PageIndex
        {
            get { return (int)GetValue(PageIndexProperty); }
            set { SetValue(PageIndexProperty, value); }
        }
        public static readonly DependencyProperty PageIndexProperty =
            DependencyProperty.Register(
                "PageIndex",
                typeof(int),
                typeof(DataPager),
                new UIPropertyMetadata(1, (sender, e) =>
                {
                    var dp = sender as DataPager;
                    if (dp == null) return;
                    dp.ChangeNavigationButtonState();
                }));

        /// <summary>
        /// 每页显示条数
        /// </summary>
        public int PageSize
        {
            get { return (int)GetValue(PageSizeProperty); }
            set { SetValue(PageSizeProperty, value); }
        }
        public static readonly DependencyProperty PageSizeProperty =
            DependencyProperty.Register(
                "PageSize",
                typeof(int),
                typeof(DataPager),
                new UIPropertyMetadata(10, (sender, e) =>
                {
                    var dp = sender as DataPager;
                    if (dp == null) return;
                    dp.InitData();
                    dp.OnPageChanging(1);
                    dp.ChangeNavigationButtonState();
                }));

        /// <summary>
        /// 总记录数量
        /// </summary>
        public int TotalCount
        {
            get { return (int)GetValue(TotalCountProperty); }
            set
            {
                SetValue(TotalCountProperty, value);
            }
        }
        public static readonly DependencyProperty TotalCountProperty =
            DependencyProperty.Register(
                "TotalCount",
                typeof(int),
                typeof(DataPager),
                new UIPropertyMetadata(0, (sender, e) =>
                {
                    var dp = sender as DataPager;
                    if (dp == null) return;
                    dp.InitData();
                    dp.ChangeNavigationButtonState();
                }));

        /// <summary>
        /// 总页数
        /// </summary>
        public int PageCount
        {
            get { return (int)GetValue(PageCountProperty); }
            private set { SetValue(PageCountProperty, value); }
        }
        public static readonly DependencyProperty PageCountProperty =
            DependencyProperty.Register("PageCount", typeof(int), typeof(DataPager), new UIPropertyMetadata(1));


        public List<int> PageSizes
        {
            get { return (List<int>)GetValue(PageSizesProperty); }
            set { SetValue(PageSizesProperty, value); }
        }

        public static readonly DependencyProperty PageSizesProperty =
            DependencyProperty.Register(
                "PageSizes",
                typeof(List<int>),
                typeof(DataPager),
                new PropertyMetadata(new List<int>() { 1, 10, 20, 30, 40, 50 })
                );

        #endregion 依赖属性

        #region 初始化
        /// <summary>
        /// 初始化数据
        /// </summary>
        void InitData()
        {
            // 根据记录总数计算总页数
            if (TotalCount == 0)
                PageCount = 1;
            else
                PageCount = TotalCount % PageSize > 0 ? (TotalCount / PageSize) + 1 : TotalCount / PageSize;

            // 防止非法数据
            if (PageIndex < 1)
                PageIndex = 1;

            if (PageIndex > PageCount)
                PageIndex = PageCount;

            if (PageSize < 1)
                PageSize = 10;
        }
        #endregion

        #region 按钮逻辑
        /// <summary>
        /// 点击首页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirst_Click(object sender, RoutedEventArgs e)
        {
            OnPageChanging(1);
        }

        /// <summary>
        /// 点击上一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrev_Click(object sender, RoutedEventArgs e)
        {
            OnPageChanging(PageIndex - 1);
        }

        /// <summary>
        /// 点击下一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            OnPageChanging(PageIndex + 1);
        }

        /// <summary>
        /// 点击末页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLast_Click(object sender, RoutedEventArgs e)
        {
            OnPageChanging(PageCount);
        }

        private void TxtPageIndex_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9]+");
            e.Handled = re.IsMatch(e.Text);
        }

        /// <summary>
        /// 点击跳转按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGoTo_Click(object sender, RoutedEventArgs e)
        {
            int pageIndex = 1;
            try
            {
                //pageIndex = Convert.ToInt32(txtPageIndex.Text);
            }
            catch
            {
            }
            finally
            {
                OnPageChanging(pageIndex);
            }
        }
        #endregion

        /// <summary>
        /// 页码更改
        /// </summary>
        /// <param name="pageIndex"></param>
        private void OnPageChanging(int pageIndex)
        {
            if (pageIndex < 1) pageIndex = 1;
            if (pageIndex > PageCount) pageIndex = PageCount;

            var eventArgs = new RoutedEventArgs(PageChangedEvent, this);
            PageIndex = pageIndex;
            RaiseEvent(eventArgs);
        }

        #region 控制按钮状态
        /// <summary>
        /// 是否可以点击首页和上一页按钮
        /// </summary>
        public bool CanGoFirstOrPrev
        {
            get
            {
                if (PageIndex <= 1) return false;
                return true;
            }
        }

        /// <summary>
        /// 是否可以点击最后页和下一页按钮
        /// </summary>
        public bool CanGoLastOrNext
        {
            get
            {
                if (PageIndex >= PageCount) return false;
                return true;
            }
        }

        /// <summary>
        /// 通知导航按钮(首页,上一页,下一页,末页)状态的更改
        /// </summary>
        void ChangeNavigationButtonState()
        {
            OnPropertyChanged("CanGoFirstOrPrev");
            OnPropertyChanged("CanGoLastOrNext");
        }

        #endregion

        #region INotifyPropertyChanged成员
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion INotifyPropertyChanged成员

        
    }
}

效果图:

相关推荐
别给迷住了1 小时前
WPF 绘制过顶点的圆滑曲线(样条,贝塞尔)
wpf·贝塞尔曲线·样条曲线·圆滑曲线·过顶点·beziersegment
白露与泡影20 小时前
Redisson分布式锁的源码解读
分布式·wpf
勇者神龟20 小时前
.net framework wpf 打包免安装exe文件
.net·wpf
吉量*1 天前
WPF系列四:图形控件Rectangle
wpf
假男孩儿2 天前
WPF 最小化到系统托盘
wpf
勇敢小菜鸟2 天前
WPF自定义窗口 输入验证不生效
wpf
鲤籽鲲2 天前
WPF TextBox 输入限制 详解
wpf
鸿喵小仙女2 天前
C# WPF读写STM32/GD32单片机Flash数据
stm32·单片机·c#·wpf
六点的晨曦2 天前
WPF的右键菜单项目引入DLL和DllImport特性引入DLL文件的异同点
wpf
一个不正经的林Sir2 天前
C#WPF基础介绍/第一个WPF程序
开发语言·c#·wpf