WPF使用MVVM实现数据分页组件

Posted huccdd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF使用MVVM实现数据分页组件相关的知识,希望对你有一定的参考价值。

 技术分享图片

 

前台代码

<UserControl x:Class="GasWpf.View.ucPage"
             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:GasWpf.View"
             mc:Ignorable="d" 
             d:DesignHeight="50" d:DesignWidth="800">
    <DockPanel Margin="12">
        <TextBlock DockPanel.Dock="Left" Margin="0,0,6,0" FontSize="16" VerticalAlignment="Center">Show</TextBlock>
        <TextBox DockPanel.Dock="Left" Width="30" MaxLength="3" FontSize="16" Text="{Binding PageSize,Mode=TwoWay}">
        </TextBox>
        <TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" FontSize="16">/ Page</TextBlock>
        <StackPanel Orientation="Horizontal" DockPanel.Dock="Right">
            <TextBlock VerticalAlignment="Center" FontSize="16" Margin="0,0,12,0">
                    <TextBlock>Total</TextBlock>
                    <TextBlock Text="{Binding Total}" Foreground="#ed4014"/>
                </TextBlock>
            <ItemsControl ItemsSource="{Binding PageNumber}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <Button Command="{Binding PageChange}" CommandParameter="{Binding Value}" ToolTip="{Binding ToolTip}" IsEnabled="{Binding IsEnabled}" Foreground="#515a6e" BorderBrush="{Binding BackGround}" Background="{Binding BackGround}" Content="{Binding Name}" Margin="3,0,3,0" />
                        </WrapPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </StackPanel>
        <TextBlock></TextBlock>
    </DockPanel>
</UserControl>

cs代码

技术分享图片
using GalaSoft.MvvmLight.Command;
using GasWpf.Model;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace GasWpf.View
{
    /// <summary>
    /// ucPage.xaml 的交互逻辑
    /// </summary>
    public partial class ucPage : UserControl
    {

        public ucPage()
        {
            InitializeComponent();
        }

        #region 每页显示的条数
        /// <summary>
        /// 注册每页数
        /// </summary>
        public static readonly DependencyProperty PageSizeProperty = 
            DependencyProperty.Register("PageSize", typeof(int), typeof(ucPage),
                new PropertyMetadata(new PropertyChangedCallback(OnPageSizeChanged)));

        /// <summary>
        /// 每页数
        /// </summary>
        public int PageSize
        {
            get { return Convert.ToInt32(GetValue(PageSizeProperty)); }
            set
            {
                SetValue(PageSizeProperty, value);
            }
        }
        #endregion

        #region 当前页
        /// <summary>
        /// 注册当前页
        /// </summary>
        public static readonly DependencyProperty PageIndexProperty = 
            DependencyProperty.Register("PageIndex", typeof(int), typeof(ucPage),
                new PropertyMetadata(new PropertyChangedCallback(OnPageChanged)));

        /// <summary>
        /// 当前页
        /// </summary>
        public int PageIndex
        {
            get { return Convert.ToInt32(GetValue(PageIndexProperty)); }
            set
            {
                SetValue(PageIndexProperty, value);
            }
        }
        private static void OnPageSizeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ucPage uc = (ucPage)sender;
            uc.PageIndex = 1;
            uc.pagination();
        }
        private static void OnPageChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ((ucPage)sender).pagination();
        }
        #endregion

        #region 总记录数
        /// <summary>
        /// 总记录数
        /// </summary>
        public static readonly DependencyProperty TotalProperty = 
            DependencyProperty.Register("Total", typeof(int), typeof(ucPage),
                new PropertyMetadata(new PropertyChangedCallback(OnPageChanged)));

        /// <summary>
        /// 总记录数
        /// </summary>
        public int Total
        {
            get { return Convert.ToInt32(GetValue(TotalProperty)); }
            set
            {
                SetValue(TotalProperty, value);
            }
        }
        #endregion

        private void pagination()
        {
            if (Total == 0 || PageSize ==0) return;

            int _totalPage = Total / PageSize;
            if (Total % PageSize > 0)
            {
                _totalPage++;
            }
            List<Paging> pn = new List<Paging>
            {
                new Paging() {
                    Name = "<",
                    ToolTip = "上一页",
                    PageChange = Changed(),
                    Value = PageIndex -1,
                    IsEnabled  = PageIndex!=1&&_totalPage!=1
                }
            };
            pn.Add(new Paging()
            {
                Name = "1",
                ToolTip = "1",
                Value = 1,
                PageChange = Changed(),
                IsEnabled = true,
                BackGround = PageIndex == 1 ? "#b39ddb" : "#ede7f6"
            });
            int begin = PageIndex >= 6 ? PageIndex - 3 : 2;
            int end = PageIndex + 3 >= _totalPage ? _totalPage - 1 : PageIndex + 3;
            for (int i = begin; i <= end; i++)
            {
                Paging p = new Paging()
                {
                    Value = i,
                    Name = i.ToString(),
                    IsEnabled = true,
                    ToolTip = i.ToString(),
                    PageChange = Changed()
                };
                if (i == PageIndex)
                {
                    p.BackGround = "#b39ddb";
                }
                if (i == begin && PageIndex - begin >= 3 && PageIndex > 5)
                {
                    p.Value = PageIndex - 5;
                    p.Name = "...";
                    p.ToolTip = "向前5页";
                }
                else if (i == end && end - PageIndex >= 3 && _totalPage - PageIndex >= 5)
                {
                    p.Value = PageIndex + 5;
                    p.Name = "...";
                    p.ToolTip = "向后5页";
                }
                pn.Add(p);
            }
            if (_totalPage > 1)
            {
                pn.Add(new Paging()
                {
                    Name = _totalPage.ToString(),
                    ToolTip = _totalPage.ToString(),
                    PageChange = Changed(),
                    Value = _totalPage,
                    IsEnabled = true,
                    BackGround = PageIndex == _totalPage ? "#b39ddb" : "#ede7f6"
                });
            }
            pn.Add(new Paging()
            {
                Name = ">",
                ToolTip = "下一页",
                Value = PageIndex + 1,
                PageChange = Changed(),
                IsEnabled = PageIndex != _totalPage && _totalPage != 1
            });
            PageNumber = pn;
        }

        private RelayCommand<int> Changed()
        {
            return new RelayCommand<int>((arg) =>
            {
                PageIndex = arg;
            });
        }

        public static readonly DependencyProperty PageNumberProperty =
            DependencyProperty.Register("PageNumber", typeof(List<Paging>), typeof(ucPage));

        /// <summary>
        /// 分页信息
        /// </summary>
        public List<Paging> PageNumber
        {
            get { return (List<Paging>)GetValue(PageNumberProperty); }
            set
            {
                SetValue(PageNumberProperty, value);
            }
        }
    }
}
View Code

ViewModel代码

技术分享图片
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GasWpf.Model;
using System;
using System.Collections.Generic;
using System.Windows.Input;

namespace GasWpf.ViewModel
{
    public class PageVM : ViewModelBase
    {

        public PageVM()
        {
        }

        private void pagination()
        {
            TotalPage = Total / PageSize;
            if (Total % PageSize > 0)
            {
                TotalPage++;
            }
            List<Paging> pn = new List<Paging>
            {
                new Paging() {
                    Name = "<",
                    ToolTip = "上一页",
                    PageChange = Changed(),
                    Value = _pageIndex -1,
                    IsEnabled  = _pageIndex!=1
                }
            };
            pn.Add(new Paging()
            {
                Name = "1",
                ToolTip = "1",
                Value =1,
                PageChange = Changed(),
                IsEnabled = true,
                BackGround = _pageIndex==1? "#b39ddb" : "#ede7f6"
            });
            int begin = _pageIndex >= 6 ? _pageIndex - 3 : 2;
            int end = _pageIndex + 3 >= TotalPage ? TotalPage-1 : _pageIndex + 3;
            for (int i = begin; i <= end; i++)
            {
                Paging p = new Paging()
                {
                    Value = i,
                    Name = i.ToString(),
                    IsEnabled = true,
                    ToolTip = i.ToString(),
                    PageChange = Changed()
                };
                if (i == _pageIndex)
                {
                    p.BackGround = "#b39ddb";
                }
                if (i == begin && _pageIndex - begin >= 3 && _pageIndex > 5)
                {
                    p.Value = _pageIndex - 5;
                    p.Name = "...";
                    p.ToolTip = "向前5页";
                }
                else if (i==end && end - _pageIndex >= 3 && TotalPage - _pageIndex >= 5)
                {
                    p.Value = _pageIndex + 5;
                    p.Name = "...";
                    p.ToolTip = "向后5页";
                }
                pn.Add(p);
            }
            if (TotalPage > 1)
            {
                pn.Add(new Paging()
                {
                    Name = TotalPage.ToString(),
                    ToolTip = TotalPage.ToString(),
                    PageChange = Changed(),
                    Value = TotalPage,
                    IsEnabled = true,
                    BackGround = _pageIndex == TotalPage ? "#b39ddb" : "#ede7f6"
                });
            }
            pn.Add(new Paging()
            {
                Name = ">",
                ToolTip = "下一页",
                Value = _pageIndex+1,
                PageChange = Changed(),
                IsEnabled = _pageIndex != TotalPage
            });
            PageNumber = pn;
        }

        private RelayCommand<int> Changed()
        {
            return new RelayCommand<int>((arg) =>
            {
                PageIndex = arg;
            });
        }

        private int _total;
        public int Total
        {
            get { return _total; }
            set { _total = value; RaisePropertyChanged(() => Total); }
        }

        private int _pageSize = 15;
        public int PageSize
        {
            get { return _pageSize; }
            set
            {
                _pageSize = value;
                RaisePropertyChanged(() => PageSize);
            }
        }

        private int _pageIndex = 1;
        public int PageIndex
        {
            get { return _pageIndex; }
            set
            {
                _pageIndex = value;
                RaisePropertyChanged(() => PageIndex);
            }
        }

        private int _totalPage = 0;
        public int TotalPage
        {
            get { return _totalPage; }
            set
            {
                _totalPage = value;
                RaisePropertyChanged(() => TotalPage);
            }
        }

        private List<Paging> _pageNumber;
        public List<Paging> PageNumber
        {
            get { return _pageNumber; }
            set
            {
                _pageNumber = value;
                RaisePropertyChanged(() => PageNumber);
            }
        }
    }
}
View Code

演示程序下载

http://www.jooand.com/case/e

以上是关于WPF使用MVVM实现数据分页组件的主要内容,如果未能解决你的问题,请参考以下文章

WPF项目学习.三

WPF MVVM 数据绑定问题

wpf MVVM框架基础

使用 Microsoft.Toolkit.Mvvm 和 Microsoft.Xaml.Behaviors.Wpf 将事件参数传递给命令

WPF MVVM从入门到精通1:MVVM模式简介

WPF 在 MVVM 模式下实现窗口后台代码与ViewModel交互