wpf制作分页控件

wpf制作分页控件wpf制作分页控件最近在学习新的项目,看到一些用winform制作的分页控件,于是想研究下wpf制作的分页控件,在网上也看到了一些,不想说其中的好坏,只是觉得对于初学者可能理解起来并不是很容易,于是根据自己的理解,将自己做的控件跟大家分享,并附上调用实例。这是我做的分页控件,前台代码如下:UserControlx:Class=”WpfApplication1.PageControl”

wpf制作分页控件

最近在学习新的项目,看到一些用winform制作的分页控件,于是想研究下wpf制作的分页控件,在网上也看到了一些,不想说其中的好坏,只是觉得对于初学者可能理解起来并不是很容易,于是根据自己的理解,将自己做的控件跟大家分享,并附上调用实例。
这里写图片描述
这是我做的分页控件,前台代码如下:

<UserControl x:Class="WpfApplication1.PageControl"
             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:WpfApplication1"
             mc:Ignorable="d" 
             d:DesignHeight="30" d:DesignWidth="350">
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50"/>
            <ColumnDefinition Width="50"/>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="50"/>
            <ColumnDefinition Width="50"/>
            <ColumnDefinition Width="50"/>
        </Grid.ColumnDefinitions>
        <Button Grid.Column="0" Content="首页" Background="White" FocusVisualStyle="{x:Null}" IsEnabled="True" Name="FirstBtn" BorderBrush="Transparent" BorderThickness="0" Click="FirstBtn_Click"/>
        <Button Grid.Column="1" Content="上一页" FocusVisualStyle="{x:Null}" Margin="5,0,0,0" Name="UpPageBtn" IsEnabled="True" Background="White" BorderBrush="Transparent" BorderThickness="0" Click="UpPageBtn_Click"/>
        <TextBox Grid.Column="2" Height="25" Width="30" Name="IndexTB" KeyDown="IndexTB_KeyDown" BorderBrush="#999999" Text="00" Padding="0,2,0,0" Margin="5,3,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" />
        <Label Grid.Column="2" Content="/100页" Name="totalPageCount" VerticalAlignment="Center" Width="60" HorizontalAlignment="Right" HorizontalContentAlignment="Left" />
        <Button Grid.Column="3" Content="跳转" Margin="5,0,0,0" FocusVisualStyle="{x:Null}" Background="White" IsEnabled="True" Name="GoToPageBtn" BorderBrush="Transparent" BorderThickness="0" Click="GoToPageBtn_Click"/>
        <Button Grid.Column="4" Margin="5,0,0,0" Content="下一页" Background="White" FocusVisualStyle="{x:Null}" IsEnabled="True" Name="NextPageBtn" BorderBrush="Transparent" BorderThickness="0" Click="NextPageBtn_Click"/>
        <Button Grid.Column="5" Margin="5,0,0,0" Content="末页" Background="White" IsEnabled="True" FocusVisualStyle="{x:Null}" Name="LastPageBtn" BorderBrush="Transparent" BorderThickness="0" Click="LastPageBtn_Click"/>
    </Grid>
</UserControl>

这里只是简单的绘制了一个分页控件,大家可以根据自己的需要去修改前台代码即可,
这里定义了一个类,里面包含一个字段,索引页,也就是我们想要查询的那一页,
public class PageControlTestEventHandler : EventArgs
{
/// <summary>
/// 页码
/// </summary>
public int PageIndex { get; set; }
public PageControlTestEventHandler(int page)
{
PageIndex = page;
}
}

且定义了一个页码改变的委托事件:

/// <summary>
        /// 页面页码改变事件
        /// </summary>
        public event EventHandler<PageControlTestEventHandler> OnPageIndexChanged;
         /// <summary>
        /// 页码改变
        /// </summary>
        /// <param name="e"></param>
        private void PageIndexChanged(PageControlTestEventHandler e)
        {
            if (OnPageIndexChanged != null) OnPageIndexChanged(this, e);

        }

这里要先定义两个属性:总页数以及当前页属性

 public int TotalPageCount
        {
            get
            {
                return _TotalPageCount;
            }
            set
            {
                //如果页面数小于1,默认为1
                if (value < 1)
                {
                    _TotalPageCount = 1;
                }
                else
                {
                    _TotalPageCount = value;
                }
                totalPageCount.Content = "/" + _TotalPageCount.ToString() + "页";
                CurrentPageIndex = 1;

            }
        }
        private int _TotalPageCount = 1;
        /// <summary>
        /// 当前页索引(从1开始)
        /// </summary>
        public int CurrentPageIndex
        {
            get
            {
                return _CurrentPageIndex;
            }
            set
            {

                PageControlTestEventHandler pceh = new PageControlTestEventHandler(value);
                PageIndexChanged(pceh);
                _CurrentPageIndex = value;
                IndexTB.Text = _CurrentPageIndex.ToString();
                FlashButtonEnable();
            }
        }
        private int _CurrentPageIndex = 1;

这里添加了一个方法用于刷新分页控件中按钮是否可用,其基本原理是:如果总页数为1,则下一页按钮、上一页按钮、末页按钮不用,首页按钮可以用;如果总页数大于1且当前页为1,上一页按钮不可用,下一页按钮、末页按钮,首页按钮可用;如果当前页大于0且当前页数小于总页数则首页按钮、上一页按钮、下一页按钮、末页按钮都可用;如果索引页为最后一页则首页按钮和上一页按钮可用,下一页按钮和末页按钮 不可用;对于跳转按钮,当待索引页小于1或大于总页数则不可用,否则跳转按钮可用。具体实现如下:

private void FlashButtonEnable()
        {
            this.Dispatcher.Invoke(new Action(() => { //总页数为1 if (_TotalPageCount == 1) { this.NextPageBtn.IsEnabled = false; UpPageBtn.IsEnabled = false; FirstBtn.IsEnabled = true; LastPageBtn.IsEnabled = false; } //当前页为1 else if (_CurrentPageIndex == 1) { FirstBtn.IsEnabled = true; UpPageBtn.IsEnabled = false; NextPageBtn.IsEnabled = true; LastPageBtn.IsEnabled = true; } //当前为中间页 else if (_CurrentPageIndex > 0 && _CurrentPageIndex < _TotalPageCount) { FirstBtn.IsEnabled = true; UpPageBtn.IsEnabled = true; NextPageBtn.IsEnabled = true; LastPageBtn.IsEnabled = true; } //当前为末页 else if (_CurrentPageIndex == _TotalPageCount) { FirstBtn.IsEnabled = true; UpPageBtn.IsEnabled = true; NextPageBtn.IsEnabled = false; LastPageBtn.IsEnabled = false; } if (int.Parse(IndexTB.Text.Trim()) < 1 || int.Parse(IndexTB.Text.Trim()) > _TotalPageCount) { GoToPageBtn.IsEnabled = false; } else { GoToPageBtn.IsEnabled = true; GoToPageBtn.Tag = int.Parse(IndexTB.Text.Trim()); } totalPageCount.Content = "/" + _TotalPageCount.ToString() + "页"; totalPageCount.Tag = _TotalPageCount; })); }`

下面是按钮事件:

 private void IndexTB_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //WindowsStateMessageArgs args = new WindowsStateMessageArgs();
                //args.StateType = WindowsStateMessageType.Enter;
                //if (WindowsStateEvent != null)
                //{ 
   
                // WindowsStateEvent(this, args);
                //}
                CurrentPageIndex = int.Parse(IndexTB.Text.Trim());
                FlashButtonEnable();

            }
        }

        private void FirstBtn_Click(object sender, RoutedEventArgs e)
        {
            //WindowsStateMessageArgs args = new WindowsStateMessageArgs();
            //args.StateType = WindowsStateMessageType.First;
            //if (WindowsStateEvent != null)
            //{ 
   
            // WindowsStateEvent(this, args);
            //}
            IndexTB.Text = "1";
            CurrentPageIndex = 1;
        }

        private void UpPageBtn_Click(object sender, RoutedEventArgs e)
        {
            //WindowsStateMessageArgs args = new WindowsStateMessageArgs();
            //args.StateType = WindowsStateMessageType.Up;
            //if (WindowsStateEvent != null)
            //{ 
   
            // WindowsStateEvent(this, args);
            //}
            CurrentPageIndex = _CurrentPageIndex - 1;
            FlashButtonEnable();
            IndexTB.Text = _CurrentPageIndex.ToString();
        }

        private void GoToPageBtn_Click(object sender, RoutedEventArgs e)
        {
            //WindowsStateMessageArgs args = new WindowsStateMessageArgs();
            //args.StateType = WindowsStateMessageType.Goto;
            //if (WindowsStateEvent != null)
            //{ 
   
            // WindowsStateEvent(this, args);
            //}
            CurrentPageIndex = int.Parse(IndexTB.Text.Trim());
            FlashButtonEnable();
        }

        private void NextPageBtn_Click(object sender, RoutedEventArgs e)
        {
            //WindowsStateMessageArgs args = new WindowsStateMessageArgs();
            //args.StateType = WindowsStateMessageType.Next;
            //if (WindowsStateEvent != null)
            //{ 
   
            // WindowsStateEvent(this, args);
            //}
            CurrentPageIndex = _CurrentPageIndex + 1;
            FlashButtonEnable();
            IndexTB.Text = _CurrentPageIndex.ToString();
        }

        private void LastPageBtn_Click(object sender, RoutedEventArgs e)
        {
            //WindowsStateMessageArgs args = new WindowsStateMessageArgs();
            //args.StateType = WindowsStateMessageType.Last;
            //if (WindowsStateEvent != null)
            //{ 
   
            // WindowsStateEvent(this, args);
            //}
            CurrentPageIndex = _TotalPageCount;
            IndexTB.Text = _TotalPageCount.ToString();
        }
         这便是分页控件的全部流程,下面附上使用实例:
<Window x:Class="WpfApplication1.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:WpfApplication1"
        mc:Ignorable="d"
        Title="Frimain" Height="470" Width="525" WindowStyle="None" AllowsTransparency="True" WindowStartupLocation="CenterScreen" Background="Transparent" Loaded="Window_Loaded">
    <Window.Resources>
        <DataTemplate x:Key="ItemTemplate">
            <Grid Height="30">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0" Content="{Binding name}"/>
                <Label Grid.Column="1" Content="{Binding unit}"/>
            </Grid>
        </DataTemplate>
    </Window.Resources>
    <Grid Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="400"/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>
        <DataGrid Name="DG" />
            <!--<Image Grid.Row="0" Name="imh" Stretch="None"  Height="150" Width="150"/>
        <Image Grid.Row="1" Name="img" Height="300" Width= "300"/>-->
        <ListBox  Name="DataList" Grid.Row="0" Height="400" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding}">
        </ListBox>
        <local:PageControl Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="pagecontrol"/>
    </Grid>
</Window>
 public partial class MainWindow : Window
    {
        public static object imgLock = new object();
        List<datamodel> data = new List<datamodel>();
        List<datamodel> showdata = new List<datamodel>();
        // 查询结果每页显示结果数
        private int PrePageRecordCount = 20;

        //查询信息开始位置
        public string currentRow
        {
            get;
            set;
        }

        // 信息获取数量
        public string fetchRow
        {
            get;
            set;
        }
        public MainWindow()
        {
            InitializeComponent();
        }
         private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            data.Clear();
            for (int i = 0; i < 80; i++)
            {
                datamodel dm = new datamodel();
                dm.name = "海鑫" + i.ToString();
                dm.unit="科金" + i.ToString();
                data.Add(dm);
            }
            if (data.Count % PrePageRecordCount > 0)
            {
                pagecontrol.TotalPageCount = data.Count / PrePageRecordCount + 1;
            }
            else
            {
                pagecontrol.TotalPageCount = data.Count / PrePageRecordCount;
            }
            pagecontrol.OnPageIndexChanged += pageControl1_OnPageIndexChanged;
            pagecontrol.CurrentPageIndex = 1;
             }
              private void pageControl1_OnPageIndexChanged(object sender, PageControlTestEventHandler e)
        {
            currentRow = (PrePageRecordCount * (e.PageIndex - 1)).ToString();//查询信息开始位置
            fetchRow = PrePageRecordCount.ToString();//查询的信息量
            showData();
        }
        private void showData()
        {
            DataList.ItemsSource = null;
            showdata.Clear();
            for (int i = int.Parse(currentRow); i < data.Count; i++)
            {
                if(showdata.Count < int.Parse(fetchRow))
                showdata.Add(data[i]);
            }
            DataList.ItemsSource = showdata;
            //dgScenePictureInfo.DataSource = null;
            ////string word = "select USERNAME, TRUE_NAME,CREATE_DATETIME from SYS_USER order by CREATE_DATETIME DESC limit " + currentRow.ToString() + "," + fetchRow.ToString();
            //string word = "select * from SYS_USER order by CREATE_DATETIME DESC limit " + currentRow.ToString() + "," + fetchRow.ToString();
            //SQLiteCommand cd = new SQLiteCommand();
            //cd.CommandText = word;
            //dataset = myclass.getDataset(cd.CommandText, "SYS_USER");
            //dgScenePictureInfo.DataSource = dataset.Tables[0];
        }
        }

今天的文章wpf制作分页控件分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/12246.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注