码迷,mamicode.com
首页 > Windows程序 > 详细

WPF MVVM 用户控件完成分页

时间:2015-11-26 18:47:01      阅读:345      评论:0      收藏:0      [点我收藏+]

标签:

项目中经常会有分页查询的情况,在WPF中我们可以通过用户控件完成分页

一下为分页控件的页面代码,

<UserControl x:Class="Foundation.UCtrl.NextPageControl"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="56" d:DesignWidth="642">
    <UserControl.Resources>
        <Style x:Key="PageButton" TargetType="Button">
            <Style.Triggers>
                <EventTrigger RoutedEvent="Button.MouseEnter">
                    <BeginStoryboard>
                        <Storyboard >
                            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" To="1" Duration="00:00:00.5000000" BeginTime="0"/>
                            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" To="1" Duration="00:00:00.5000000" BeginTime="0" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="Button.MouseLeave">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" To="1" Duration="00:00:00.5000000" BeginTime="0"/>
                            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" To="1" Duration="00:00:00.5000000" BeginTime="0"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="Button.Click">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" To="0.8" Duration="00:00:00.2000000" BeginTime="0" AutoReverse="True"/>
                            <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" To="0.8" Duration="00:00:00.2000000" BeginTime="0" AutoReverse="True"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </UserControl.Resources>
    <Grid Height="50" Width="637">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="232*"/>
            <ColumnDefinition Width="58*"/>
            <ColumnDefinition Width="58*"/>
            <ColumnDefinition Width="58*"/>
            <ColumnDefinition Width="58*"/>
            <ColumnDefinition Width="78*"/>
        </Grid.ColumnDefinitions>
        <StackPanel Orientation="Horizontal" Grid.Column="0">
            <Label FontSize="14" Margin="0 7 0 0" Foreground="#FF3575A0"  Content=""/>
            <Label FontSize="14" Margin="0 7 0 0" Foreground="#FF3575A0" Content="{Binding Path=TotalPage,Mode=TwoWay}" Name="lblTotalPage" />
            <Label FontSize="14" Margin="0 7 0 0" Foreground="#FF3575A0"  Content=""/>
            <Label FontSize="14" Margin="0 7 0 0" Foreground="#FF3575A0"  Content="当前第"/>
            <Label FontSize="14" Margin="0 7 0 0" Foreground="#FF3575A0"  Name="lblCurrentPage" Content="{Binding Path=CurrentPage,Mode=TwoWay}" />
            <Label FontSize="14" Margin="0 7 0 0" Foreground="#FF3575A0"  Content=""/>
            <Label FontSize="14" Margin="0 7 0 0" Foreground="#FF3575A0"  Content="每页 "/>
            <Label FontSize="14" Margin="0 7 0 0" Foreground="#FF3575A0"  Name="lblPageSize" Content="{Binding Path=PageSize,Mode=TwoWay}"/>
            <Label FontSize="14" Margin="0 7 0 0" Foreground="#FF3575A0"  Content=""/>
        </StackPanel>
        <Button Width="48" Height="48"   Style="{StaticResource PageButton}"  Grid.Column="1" BorderThickness="0" Name="btnFrist" Click="btnFrist_Click" Cursor="Hand">
            <Button.RenderTransform>
                <ScaleTransform CenterX="24" CenterY="24" ScaleX="1" ScaleY="1"/>
            </Button.RenderTransform>
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Images\NextPage\button_begin.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <Button Width="48" Height="48"  Style="{StaticResource PageButton}" Grid.Column="2" BorderThickness="0" Name="btnRew" Click="btnRew_Click"  Cursor="Hand">
            <Button.RenderTransform>
                <ScaleTransform CenterX="24" CenterY="24" ScaleX="1" ScaleY="1"/>
            </Button.RenderTransform>
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Images\NextPage\button_rew.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <Button Width="48" Height="48"  Style="{StaticResource PageButton}" Grid.Column="3" BorderThickness="0" Name="btnFF" Click="btnFF_Click" Cursor="Hand">
            <Button.RenderTransform>
                <ScaleTransform CenterX="24" CenterY="24" ScaleX="1" ScaleY="1"/>
            </Button.RenderTransform>
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Images\NextPage\button_ff.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <Button Width="48" Height="48"  Style="{StaticResource PageButton}" Grid.Column="4" BorderThickness="0" Name="btnLast" Click="btnLast_Click" Cursor="Hand">
            <Button.RenderTransform>
                <ScaleTransform CenterX="24" CenterY="24" ScaleX="1" ScaleY="1"/>
            </Button.RenderTransform>
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Images\NextPage\button_end.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <Button Width="48" Height="48"  Style="{StaticResource PageButton}" Grid.Column="6" BorderThickness="0" Name="btnRefresh" Click="btnRefresh_Click" Cursor="Hand">
            <Button.RenderTransform>
                <ScaleTransform CenterX="24" CenterY="24" ScaleX="1" ScaleY="1"/>
            </Button.RenderTransform>
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Images\NextPage\button_rotate_ccw.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
    </Grid>
</UserControl>
NextPageControl的后台代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 using System.Windows;
  7 using System.Windows.Controls;
  8 using System.Windows.Data;
  9 using System.Windows.Documents;
 10 using System.Windows.Input;
 11 using System.Windows.Media;
 12 using System.Windows.Media.Imaging;
 13 using System.Windows.Navigation;
 14 using System.Windows.Shapes;
 15 
 16 namespace TestNextPage
 17 {
 18     /// <summary>
 19     /// NextPageControl.xaml 的交互逻辑
 20     /// </summary>
 21     public partial class NextPageControl : UserControl
 22     {
 23         //定义一个委托
 24         public delegate void PageChangedHandle(object sender, EventArgs e);
 25         //定义一个事件
 26         public event PageChangedHandle PageChanged;
 27 
 28         public NextPageControl()
 29         {
 30             InitializeComponent();
 31 
 32         }
 33         //总页数
 34         private int totalPage = 1;
 35         /// <summary>
 36         /// 当前页
 37         /// </summary>
 38         private int currentPage = 1;
 39 
 40         #region 每页显示的条数
 41         /// <summary>
 42         /// 注册当前页
 43         /// </summary>
 44         public static readonly DependencyProperty PageSizeProperty = DependencyProperty.Register("PageSize", typeof(String),
 45         typeof(NextPageControl), new FrameworkPropertyMetadata("1", FrameworkPropertyMetadataOptions.AffectsMeasure), new ValidateValueCallback(CurrentPageValidation));
 46 
 47         /// <summary>
 48         /// 验证当前页
 49         /// </summary>
 50         /// <param name="value"></param>
 51         /// <returns></returns>
 52         public static bool PageSizeValidation(object value)
 53         {
 54             return true;
 55         }
 56         /// <summary>
 57         /// 当前页
 58         /// </summary>
 59         public string PageSize
 60         {
 61             get { return GetValue(NextPageControl.PageSizeProperty).ToString(); }
 62             set
 63             {
 64                 SetValue(NextPageControl.PageSizeProperty, value);
 65                 lblPageSize.Content = value;
 66             }
 67         }
 68         #endregion
 69 
 70         #region 当前页
 71         /// <summary>
 72         /// 注册当前页
 73         /// </summary>
 74         public static readonly DependencyProperty CurrentPageProperty = DependencyProperty.Register("CurrentPage", typeof(String),
 75         typeof(NextPageControl), new FrameworkPropertyMetadata("1", FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnCurrentPageChanged)), new ValidateValueCallback(CurrentPageValidation));
 76 
 77         /// <summary>
 78         /// 验证当前页
 79         /// </summary>
 80         /// <param name="value"></param>
 81         /// <returns></returns>
 82         public static bool CurrentPageValidation(object value)
 83         {
 84             return true;
 85         }
 86         /// <summary>
 87         /// 当前页
 88         /// </summary>
 89         public string CurrentPage
 90         {
 91             get { return GetValue(NextPageControl.CurrentPageProperty).ToString(); }
 92             set
 93             {
 94                 SetValue(NextPageControl.CurrentPageProperty, value);
 95 
 96                 lblCurrentPage.Content = value;
 97             }
 98         }
 99 
100 
101         #endregion
102 
103         #region 总页数
104         /// <summary>
105         /// 总页数
106         /// </summary>
107         public static readonly DependencyProperty TotalPageProperty = DependencyProperty.Register("TotalPage", typeof(String), typeof(NextPageControl), new FrameworkPropertyMetadata("1", FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnTotalPageChanged)), new ValidateValueCallback(TotalPageValidation));
108 
109         /// <summary>
110         /// 总页数进行验证
111         /// </summary>
112         /// <param name="value"></param>
113         /// <returns></returns>
114         public static bool TotalPageValidation(object value)
115         {
116             return true;
117         }
118         /// <summary>
119         /// 总页数
120         /// </summary>
121         public string TotalPage
122         {
123             get { return GetValue(NextPageControl.TotalPageProperty).ToString(); }
124             set
125             {
126                 SetValue(NextPageControl.TotalPageProperty, value);
127 
128             }
129         }
130 
131         #endregion
132 
133         #region 私有方法
134         /// <summary>
135         /// 值改变方法将由此方法来引发事件
136         /// </summary>
137         private void PageChangedFunc()
138         {
139             if (PageChanged != null)
140             {
141                 ///引发事件
142                 PageChanged(this, new EventArgs());
143             }
144         }
145 
146 
147         #endregion
148 
149         /// <summary>
150         /// 首页
151         /// </summary>
152         /// <param name="sender"></param>
153         /// <param name="e"></param>
154         private void btnFrist_Click(object sender, RoutedEventArgs e)
155         {
156             CurrentPage = "1";
157             PageChangedFunc();
158 
159         }
160         /// <summary>
161         /// 前一页
162         /// </summary>
163         /// <param name="sender"></param>
164         /// <param name="e"></param>
165         private void btnRew_Click(object sender, RoutedEventArgs e)
166         {
167             totalPage = GetIntVal(TotalPage);
168             currentPage = GetIntVal(CurrentPage);
169             if (currentPage > 1)
170             {
171                 currentPage = currentPage - 1;
172                 CurrentPage = currentPage.ToString();
173             }
174             PageChangedFunc();
175         }
176         /// <summary>
177         /// 后一页
178         /// </summary>
179         /// <param name="sender"></param>
180         /// <param name="e"></param>
181         private void btnFF_Click(object sender, RoutedEventArgs e)
182         {
183             currentPage = GetIntVal(CurrentPage);
184             totalPage = GetIntVal(TotalPage);
185             if (currentPage < totalPage)
186             {
187                 currentPage = currentPage + 1;
188                 CurrentPage = currentPage.ToString();
189             }
190             PageChangedFunc();
191         }
192         //尾页
193         private void btnLast_Click(object sender, RoutedEventArgs e)
194         {
195             currentPage = GetIntVal(TotalPage);
196             CurrentPage = currentPage.ToString();
197             PageChangedFunc();
198         }
199 
200         /// <summary>
201         /// 刷新当前页
202         /// </summary>
203         /// <param name="sender"></param>
204         /// <param name="e"></param>
205         private void btnRefresh_Click(object sender, RoutedEventArgs e)
206         {
207             PageChangedFunc();
208         }
209 
210         private int GetIntVal(string val)
211         {
212             int temp = 0;
213             if (!int
214                 .TryParse(val, out temp))
215             {
216                 temp = 1;
217             }
218             return temp;
219         }
220         /// <summary>
221         /// 当当前页值改变
222         /// </summary>
223         /// <param name="sender"></param>
224         /// <param name="e"></param>
225         private static void OnTotalPageChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
226         {
227 
228             //MyButton hsb = (MyButton)sender;
229             //  SetValue(NextPageControl.CurrentPageProperty, "1");
230            // SetFunc();
231             //Image image = hsb.tehImage;
232             //CurrentPage = "1";
233             //image.Source = new BitmapImage((Uri)e.NewValue);
234         }
235         /// <summary>
236         /// 当当前页值改变
237         /// </summary>
238         /// <param name="sender"></param>
239         /// <param name="e"></param>
240         private static void OnCurrentPageChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
241         {
242 
243             //MyButton hsb = (MyButton)sender;
244             //  SetValue(NextPageControl.CurrentPageProperty, "1");
245             // ShowMsg("event");
246             //Image image = hsb.tehImage;
247             //CurrentPage = "1";
248             //image.Source = new BitmapImage((Uri)e.NewValue);
249         }
250 
251     }
252 }

在完成分页控件以后

定义View,注意View中需要添加System.Windows.Interactivity 这个Dll

 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

需要通过它来转换事件toCommand

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TestNextPage" x:Class="TestNextPage.MainWindow"
        Title="MainWindow" Height="350" Width="700">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="45"></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Grid.Row="0">
            <Button Content="查询" Command="{Binding Path=QueryCommand}"/>
        </StackPanel>
        <DataGrid Grid.Row="1" 
                  HeadersVisibility="Column" VerticalGridLinesBrush="WhiteSmoke"
                  AutoGenerateColumns="False" CanUserAddRows="False" SelectionUnit="FullRow"
                  ItemsSource="{Binding Path=ArchiveModels,Mode=TwoWay}"   >
            <DataGrid.Columns>
                <DataGridTextColumn Header="文件编号" Width="130" IsReadOnly="True"  Binding="{Binding Path=Id}"/>
                <DataGridTextColumn Header="文件名称" Width="130" IsReadOnly="True" Binding="{Binding Path=ArchiveName}" />
            </DataGrid.Columns>
        </DataGrid>
        <local:NextPageControl Grid.Row="2" x:Name="nextPageControl1"  TotalPage="{Binding Path=TotalPage,Mode=TwoWay}" PageSize="{Binding Path=PageSize,Mode=TwoWay}" CurrentPage="{Binding Path=CurrentPage,Mode=TwoWay}">
                <i:Interaction.Triggers>
                    <i:EventTrigger  EventName="PageChanged">
                        <i:InvokeCommandAction  Command="{Binding Path=NextPageSearchCommand, Mode=TwoWay}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
        </local:NextPageControl>
    </Grid>
    
</Window>

后台

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.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestNextPage
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainWindowViewModel();
            DataContext = vm;
        }
    }
}

ViewModel代码

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.CommandWpf;

namespace TestNextPage
{
    public class MainWindowViewModel : BaseViewModel
    {
        public MainWindowViewModel()
        {
            InitTestData();
        }

        private ObservableCollection<ArchiveModel> _archiveModels;
        public ObservableCollection<ArchiveModel> ArchiveModels
        {
            get { return _archiveModels; }
            set
            {
                _archiveModels = value;
                RaisePropertyChanged();
            }

        }
        public RelayCommand QueryCommand { get; set; }

        private async void QueryCommandFunc()
        {
            await Task.Run(() =>
                {
                    int totalCount = 0;
                    ArchiveModels = GetData(PageSize, out totalCount);
                    if (totalCount % PageSize == 0)
                    {
                        TotalPage = (totalCount / PageSize).ToString();
                    }
                    else
                    {
                        TotalPage = ((totalCount / PageSize) + 1).ToString();
                    }

                });
        }

        #region 分页相关属性

        /// <summary>
        /// 分页查询命令
        /// </summary>
        private async void NextPageSearchCommandFunc()
        {
            await Task.Run(() =>
            {
                var pageIndex = Convert.ToInt32(CurrentPage);
                ArchiveModels = QueryData(pageIndex, PageSize);
            });
        }
        private string _totalPage = string.Empty;
        /// <summary>
        /// 总页数
        /// </summary>
        public string TotalPage
        {
            get { return _totalPage; }
            set
            {
                _totalPage = value;
                RaisePropertyChanged();
            }
        }

        private string _currentPage = "1";
        /// <summary>
        /// 当前页
        /// </summary>
        public string CurrentPage
        {
            get { return _currentPage; }
            set
            {
                _currentPage = value;
                RaisePropertyChanged();
            }
        }

        private int _pageSize = 40;
        /// <summary>
        /// 每页显示的记录数
        /// </summary>
        public int PageSize
        {
            get { return _pageSize; }
            set
            {
                _pageSize = value;
                RaisePropertyChanged();
            }
        }
        private int _pageIndex;
        private int _totalCount;
        public int PageIndex
        {
            get { return _pageIndex; }
            set
            {
                _pageIndex = value;

                RaisePropertyChanged();
            }
        }

        public int TotalCount
        {
            get { return _totalCount; }
            set
            {
                _totalCount = value;

                RaisePropertyChanged();
            }
        }
        /// <summary>
        /// 分页管理
        /// </summary>
        public RelayCommand NextPageSearchCommand { get; set; }

        #endregion


        private ObservableCollection<ArchiveModel> GetData(int pageSize, out int totalCount)
        {
            totalCount = 10000;
            var data = new ObservableCollection<ArchiveModel>();
            for (int i = 0; i < pageSize; i++)
            {
                data.Add(new ArchiveModel() { Id = i + 1, ArchiveName = string.Format("ArchiveName{0}", i) });
            }
            return data;
        }

        private ObservableCollection<ArchiveModel> QueryData(int pageIndex, int pageSize)
        {
            var data = new ObservableCollection<ArchiveModel>();
            for (int i = 0; i < pageSize; i++)
            {
                data.Add(new ArchiveModel() { Id = (pageIndex - 1) * pageSize + i, ArchiveName = string.Format("ArchiveName{0}", i) });
            }
            return data;
        }

        private void InitTestData()
        {
            QueryCommand = new RelayCommand(QueryCommandFunc);
            NextPageSearchCommand = new RelayCommand(NextPageSearchCommandFunc);

        }
    }
}

那么附件就是这个分页示例吧

 http://files.cnblogs.com/files/koujian/TestNextPage.rar

WPF MVVM 用户控件完成分页

标签:

原文地址:http://www.cnblogs.com/koujian/p/4998479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!