Two Days wpf 分享 分页组件

迟来的wpf分享。

目录

一、序言

二、前期准备

三、前端界面

四、后台代码部分

1、先定义些变量后面使用

2、先是按钮事件代码。

首页按钮

上一页按钮

下一页按钮

末尾按钮

画每页显示等数据

每页显示多少条

判断是否为数字的事件

分页数字的点击触发事件

跳转到多少页

3、泛型数据集合

设置页面多少

4、DataTable数据类型的

5、用户组件初始化

五、效果技术用方法

使用方法

效果

总结


一、序言

这里使用的工具是VS2019,.net版本使用的是4.5版本。素材插件使用的是materialDesign。分享是随缘更新

二、前期准备

1、现在Nuget里安装MaterialDesignColors,MaterialDesignThemes两个插件包。

2、在App.xaml文件里更改成下面代码部分

cs 复制代码
<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <!--<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml" />-->
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
                <!--<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Blue.xaml" />-->
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Blue.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

3、在所需要使用的界面里引用materialDesign,在这个位置添加如下代码:

XML 复制代码
 xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"

三、前端界面

前期工作做好了,开始写前端。这里写的是用户组件

前端代码如下:

XML 复制代码
<UserControl x:Class="ComponentLibrary.WPF.UserControls.PagingTUserControl"
             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:ComponentLibrary.WPF.UserControls"
             mc:Ignorable="d" 
            >
    <Grid>
        <Border CornerRadius="3" Background="Transparent" BorderBrush="{x:Null}">
            <Grid HorizontalAlignment="Stretch" Margin="5 0 5 0" VerticalAlignment="Top" Width="Auto" Height="30">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="150"/>
                    <ColumnDefinition Width="150"/>
                    <ColumnDefinition Width="auto" MinWidth="500"/>
                </Grid.ColumnDefinitions>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Label Content="每页显示:" HorizontalAlignment="Right"/>
                    <ComboBox x:Name="comInt" PreviewMouseDown="comInt_PreviewMouseDown" Grid.Column="1"/>
                </Grid>
                <TextBlock Name="tbkRecords" Grid.Column="1" Foreground="White" Style="{StaticResource PageTextBlock1}" />
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Column="2">
                    <Grid>
                        <Grid.RowDefinitions >
                            <RowDefinition Height="50"></RowDefinition>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="50"/>
                            <ColumnDefinition Width="30"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Name="btnFirst" Text="首页"  IsEnabled="False" Style="{StaticResource FancyTextBlockStyle2}" />
                        <TextBlock Grid.Column="1" Name="btnPrev" Text="上一个" IsEnabled="False" Style="{StaticResource FancyTextBlockStyle2}" />
                        <Grid Grid.Column="2" Name="grid" >
                            <Grid.RowDefinitions>
                                <RowDefinition Height="30" ></RowDefinition>
                            </Grid.RowDefinitions>
                        </Grid>
                        <TextBlock Grid.Column="3" x:Name="btnNext" Text="下一个" IsEnabled="False" Style="{StaticResource FancyTextBlockStyle2}" />
                        <TextBlock Grid.Column="4" x:Name="btnLast"  Text="未页" IsEnabled="False" Style="{StaticResource FancyTextBlockStyle2}"/>
                        <TextBox Grid.Column="5" x:Name="pageGo" Visibility="Collapsed" MaxLength="6" IsReadOnly="True" Style="{StaticResource PageTextBox}" />
                        <Button Grid.Column="6" x:Name="btnGo" Visibility="Collapsed" Content="GO" IsEnabled="False" Style="{StaticResource PageButton}" />
                    </Grid>
                </StackPanel>
            </Grid>
        </Border>
    </Grid>
</UserControl>

这是它的一个原型。

四、后台代码部分

这里后台写了两种数据模式一个是泛型数据类型,一个是DataTable数据类型。两种下面代码会逐一分享给大家。

1、先定义些变量后面使用

cs 复制代码
private DataTable _dt = new DataTable();        
/// <summary>
        /// 每页显示多少条
        /// </summary>
        private int pageNum = 10;
        /// <summary>
        /// 当前是第几页
        /// </summary>
        private int pIndex = 1;
        /// <summary>
        /// 对象
        /// </summary>
        private DataGrid grdList;
        /// <summary>
        /// 最大页数
        /// </summary>
        private int MaxIndex = 1;
        /// <summary>
        /// 一共多少条
        /// </summary>
        private int allNum = 0;
        /// <summary>
        /// 声明一个泛型对象接受数据.
        /// </summary>
        private List<object> obj;

2、先是按钮事件代码。

首页按钮

cs 复制代码
#region 首页

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirst_Click(object sender, System.EventArgs e)
        {
            this.pIndex = 1;
            ReadLsitT();
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirst_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        #endregion

上一页按钮

cs 复制代码
 #region 上一页
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrev_Click(object sender, System.EventArgs e)
        {
            if (this.pIndex <= 1)
                return;
            this.pIndex--;
            ReadLsitT();
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrev_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        #endregion

下一页按钮

cs 复制代码
 #region 下一页

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, System.EventArgs e)
        {
            if (this.pIndex >= this.MaxIndex)
                return;
            this.pIndex++;
            ReadLsitT();
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        #endregion

末尾按钮

cs 复制代码
 #region 未页

        /// <summary>
        /// 未页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLast_Click(object sender, System.EventArgs e)
        {
            this.pIndex = this.MaxIndex;
            ReadLsitT();
        }

        /// <summary>
        /// 未页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLast_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        #endregion

画每页显示等数据

cs 复制代码
 #region 画每页显示等数据

        /// <summary>
        /// 画每页显示等数据
        /// </summary>
        private void DisplayPagingInfo()
        {
            if (this.pIndex == 1)
            {
                this.btnPrev.IsEnabled = false;
                this.btnFirst.IsEnabled = false;
            }
            else
            {
                this.btnPrev.IsEnabled = true;
                this.btnFirst.IsEnabled = true;
            }
            if (this.pIndex == this.MaxIndex)
            {
                this.btnNext.IsEnabled = false;
                this.btnLast.IsEnabled = false;
            }
            else
            {
                this.btnNext.IsEnabled = true;
                this.btnLast.IsEnabled = true;
            }
            this.tbkRecords.Text = string.Format("每页{0}条/共{1}条", this.pageNum, this.allNum);
            int first = (this.pIndex - 4) > 0 ? (this.pIndex - 4) : 1;
            int last = (first + 9) > this.MaxIndex ? this.MaxIndex : (first + 9);
            this.grid.Children.Clear();
            for (int i = first; i <= last; i++)
            {
                ColumnDefinition cdf = new ColumnDefinition();
                this.grid.ColumnDefinitions.Add(cdf);
                TextBlock tbl = new TextBlock();
                tbl.Text = i.ToString();
                tbl.Style = FindResource("FancyTextBlockStyle3") as Style;
                tbl.MouseLeftButtonUp += new MouseButtonEventHandler(tbl_MouseLeftButtonUp);
                tbl.MouseLeftButtonDown += new MouseButtonEventHandler(tbl_MouseLeftButtonDown);
                if (i == this.pIndex)
                    tbl.IsEnabled = false;
                Grid.SetColumn(tbl, this.grid.ColumnDefinitions.Count - 1);
                Grid.SetRow(tbl, 0);
                this.grid.Children.Add(tbl);
            }
        }

        #endregion

每页显示多少条

cs 复制代码
   #region 每页显示多少条.
        private void comInt_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            // 获取点击的 ComboBoxItem
            ComboBoxItem clickedItem = FindAncestor<ComboBoxItem>((DependencyObject)e.OriginalSource);

            if (clickedItem != null)
            {
                // 获取点击项的内容(显示的文本)
                string clickedText = clickedItem.Content.ToString();
                this.pageNum = int.Parse(clickedText);

                SetMaxIndexList();
                ReadLsitT();

            }
        }

        /// <summary>
        /// 鼠标点击到combobox选项事件.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="current"></param>
        /// <returns></returns>
        private T FindAncestor<T>(DependencyObject current) where T : DependencyObject
        {
            do
            {
                if (current is T ancestor)
                {
                    return ancestor;
                }
                current = VisualTreeHelper.GetParent(current);
            }
            while (current != null);

            return null;
        }

        #endregion

判断是否为数字的事件

cs 复制代码
 private static Regex RegNumber = new Regex("^[0-9]+$");

        #region 判断是否是数字
        /// <summary>
        /// 判断是否是数字
        /// </summary>
        /// <param name="valString"></param>
        /// <returns></returns>
        public static bool IsNumber(string valString)
        {
            Match m = RegNumber.Match(valString);
            return m.Success;
        }
        #endregion

分页数字的点击触发事件

cs 复制代码
  #region 分页数字的点击触发事件

        private void tbl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            TextBlock tbl = sender as TextBlock;
            if (tbl == null)
                return;
            int index = int.Parse(tbl.Text.ToString());
            this.pIndex = index;
            if (index > this.MaxIndex)
                this.pIndex = this.MaxIndex;
            if (index < 1)
                this.pIndex = 1;
            ReadLsitT();
        }

        void tbl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        #endregion

跳转到多少页

cs 复制代码
  #region 跳转到多少页

        /// <summary>
        /// 跳转到多少页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGo_Click(object sender, RoutedEventArgs e)
        {
            if (IsNumber(this.pageGo.Text))
            {
                int pageNum = int.Parse(this.pageGo.Text);
                if (pageNum > 0 && pageNum <= this.MaxIndex)
                {
                    this.pIndex = pageNum;
                    ReadLsitT();
                }
                else if (pageNum > this.MaxIndex)
                {
                    this.pIndex = this.MaxIndex;
                    ReadLsitT();
                }
            }
            this.pageGo.Text = "";
        }

        #endregion

3、泛型数据集合

cs 复制代码
 /// <summary>
        /// 定义一个泛型来接受数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public void GenericMethod<T>(List<T> parameter)
        {
            var data = parameter;
            obj = parameter.Cast<object>().ToList();
        }

        #region  返回泛型集合

        /// <summary>
        /// 初始化数据.
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="dataGrid">数据展示表格</param>
        /// <param name="parameter">泛型</param>
        /// <param name="Num">数量</param>
        public void ShowPageT<T>(DataGrid dataGrid, List<T> parameter, int Num)
        {
            if (parameter == null || parameter.Count == 0)
                return;
            if (parameter.Count == 0)
                return;
            this.grdList = dataGrid;
            this.pageNum = Num;
            this.pIndex = 1;
            obj = parameter.Cast<object>().ToList();
            SetMaxIndexList();
            ReadLsitT();
            if (this.MaxIndex > 1)
            {
                this.pageGo.IsReadOnly = false;
                this.btnGo.IsEnabled = true;
            }
        }

        /// <summary>
        /// 画数据
        /// </summary>
        public void ReadLsitT()
        {
            try
            {
                int first = this.pageNum * (this.pIndex - 1);
                first = (first > 0) ? first : 0;
                this.grdList.ItemsSource = obj.Skip((this.pIndex - 1) * pageNum).Take(pageNum);
            }
            catch
            {
                MessageBox.Show("错误");
            }
            finally
            {
                DisplayPagingInfo();
            }
        }

        #endregion

上述的GenericMethod方法已经我这里没用使用你们可以参考使用扩展。

设置页面多少

cs 复制代码
#region 设置最多大页面
        /// <summary>
        /// 设置最多大页面
        /// </summary>
        public void SetMaxIndexList()
        {
            //多少页
            int Pages = this.obj.Count / pageNum;
            if (this.obj.Count != (Pages * pageNum))
            {
                if (this.obj.Count < (Pages * pageNum))
                    Pages--;
                else
                    Pages++;
            }
            this.MaxIndex = Pages;
            this.allNum = this.obj.Count;
        }

        #endregion

4、DataTable数据类型的

cs 复制代码
 #region 初始化数据

        /// <summary>
        /// 初始化数据datatable类型
        /// </summary>
        /// <param name="grd"></param>
        /// <param name="dtt"></param>
        /// <param name="Num"></param>
        public void ShowPages(DataGrid grd, DataTable ds,int ss)
        {
            if (ds == null || ds.Rows.Count == 0)
                return;
            if (ds.Rows.Count == 0)
                return;
            ds.DefaultView.Sort = "Date DESC";
            DataTable dt = ds.DefaultView.ToTable();
            this._dt = dt.Clone();
            this.grdList = grd;
            //this.pageNum = Num;
            this.pIndex = 1;
            foreach (DataRow r in dt.Rows)
                this._dt.ImportRow(r);
            SetMaxIndex();
            ReadDataTable();
            if (this.MaxIndex > 1)
            {
                this.pageGo.IsReadOnly = false;
                this.btnGo.IsEnabled = true;
            }
        }    

        #endregion

        #region 画数据

        /// <summary>
        /// 画数据
        /// </summary>
        private void ReadDataTable()
        {
            try
            {
                DataTable tmpTable = new DataTable();
                tmpTable = this._dt.Clone();
                int first = this.pageNum * (this.pIndex - 1);
                first = (first > 0) ? first : 0;
                //如果总数量大于每页显示数量
                if (this._dt.Rows.Count >= this.pageNum * this.pIndex)
                {
                    for (int i = first; i < pageNum * this.pIndex; i++)
                        tmpTable.ImportRow(this._dt.Rows[i]);
                }
                else
                {
                    for (int i = first; i < this._dt.Rows.Count; i++)
                        tmpTable.ImportRow(this._dt.Rows[i]);
                }
                this.grdList.ItemsSource = tmpTable.DefaultView;
                tmpTable.Dispose();
            }
            catch
            {
                MessageBox.Show("错误");
            }
            finally
            {
                DisplayPagingInfo();
            }
        }

        

        #endregion

5、用户组件初始化

cs 复制代码
 this.Loaded += delegate
            {
                //首页
                this.btnFirst.MouseLeftButtonUp += new MouseButtonEventHandler(btnFirst_Click);
                this.btnFirst.MouseLeftButtonDown += new MouseButtonEventHandler(btnFirst_MouseLeftButtonDown);
                //上一页
                this.btnPrev.MouseLeftButtonUp += new MouseButtonEventHandler(btnPrev_Click);
                this.btnPrev.MouseLeftButtonDown += new MouseButtonEventHandler(btnPrev_MouseLeftButtonDown);
                //下一页
                this.btnNext.MouseLeftButtonUp += new MouseButtonEventHandler(btnNext_Click);
                this.btnNext.MouseLeftButtonDown += new MouseButtonEventHandler(btnNext_MouseLeftButtonDown);
                //末页
                this.btnLast.MouseLeftButtonUp += new MouseButtonEventHandler(btnLast_Click);
                this.btnLast.MouseLeftButtonDown += new MouseButtonEventHandler(btnLast_MouseLeftButtonDown);
                this.btnGo.Click += new RoutedEventHandler(btnGo_Click);
            };

五、效果及使用方法

使用方法

这是我只展示泛型的使用方法

cs 复制代码
public void LogData()
        {
            try
            {
                LogDal logDal = new LogDal();
                GlobalVariable.GlobalLog = logDal.QueryById<LogTable>().OrderByDescending(m => m.Date).ToList();
                this.Page.ShowPage1(this.logDataGrid, GlobalVariable.GlobalLog, 20); //这里是调用设置分页的函数
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

只需要把你数据源和数据显示datagrid传递过去即可,填写一个默认的每页显示的条数。

别忘了引用你的用户组卷目录。

效果

总结

到此分享结束,源代码都在文章中简单整理即可使用。分享及随缘,下次什么时候分享看缘分吧。

相关推荐
2601_9629666442 分钟前
统计学专业应聘企业经营管理管培生,2027届校招的准备重点
大数据·数据分析
协皓家具1 小时前
2026年广州岛台吧台椅厂家有啥新变化
大数据·运维·python·devops
2601_962966641 小时前
大数据管理与应用专业2027届选岗,品类运营和商品运营的能力要求差异
大数据
和裕1 小时前
定制纸箱刀模费全解析:费用定义与可减免合作场景
大数据·运维·网络·人工智能·算法
归秋1423 小时前
2026企业AI办公工具选型指南:从场景匹配到平台评估
大数据·运维·人工智能
智圣新创013 小时前
教育数据要素流通刚需下 智圣新创高校数据中台解决方案的全域建设落地框架
大数据·人工智能·物联网
XLYcmy4 小时前
PDF 论文处理器 — 优势与功能文档
大数据·python·网络安全·pdf·dify·rag·漏洞检测
互联网资讯4 小时前
本地创业者入局 AI 短剧,本地化部署怎么选更省钱
大数据·人工智能
小猴子爱上树4 小时前
跨马翻译:批量图片翻译+视频字幕+智能抠图,跨境电商在线图片翻译工具
大数据·人工智能·python·音视频
W***25924 小时前
2026 企业 AI 办公工具怎么选:选型框架与平台全景分析
大数据·人工智能