WPF MVVM 用户控件完成分页
项目中经常会有分页查询的情况,在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="" d:DesignWidth="">
<UserControl.Resources>
<Style x:Key="PageButton" TargetType="Button">
<Style.Triggers>
<EventTrigger RoutedEvent="Button.MouseEnter">
<BeginStoryboard>
<Storyboard >
<DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" To="" Duration="00:00:00.5000000" BeginTime=""/>
<DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" To="" Duration="00:00:00.5000000" BeginTime="" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="Button.MouseLeave">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" To="" Duration="00:00:00.5000000" BeginTime=""/>
<DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" To="" Duration="00:00:00.5000000" BeginTime=""/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" To="0.8" Duration="00:00:00.2000000" BeginTime="" AutoReverse="True"/>
<DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" To="0.8" Duration="00:00:00.2000000" BeginTime="" AutoReverse="True"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<Grid Height="" Width="">
<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="">
<Label FontSize="" Margin="0 7 0 0" Foreground="#FF3575A0" Content="共"/>
<Label FontSize="" Margin="0 7 0 0" Foreground="#FF3575A0" Content="{Binding Path=TotalPage,Mode=TwoWay}" Name="lblTotalPage" />
<Label FontSize="" Margin="0 7 0 0" Foreground="#FF3575A0" Content="页"/>
<Label FontSize="" Margin="0 7 0 0" Foreground="#FF3575A0" Content="当前第"/>
<Label FontSize="" Margin="0 7 0 0" Foreground="#FF3575A0" Name="lblCurrentPage" Content="{Binding Path=CurrentPage,Mode=TwoWay}" />
<Label FontSize="" Margin="0 7 0 0" Foreground="#FF3575A0" Content="页"/>
<Label FontSize="" Margin="0 7 0 0" Foreground="#FF3575A0" Content="每页 "/>
<Label FontSize="" Margin="0 7 0 0" Foreground="#FF3575A0" Name="lblPageSize" Content="{Binding Path=PageSize,Mode=TwoWay}"/>
<Label FontSize="" Margin="0 7 0 0" Foreground="#FF3575A0" Content=" 条"/>
</StackPanel>
<Button Width="" Height="" Style="{StaticResource PageButton}" Grid.Column="" BorderThickness="" Name="btnFrist" Click="btnFrist_Click" Cursor="Hand">
<Button.RenderTransform>
<ScaleTransform CenterX="" CenterY="" ScaleX="" ScaleY=""/>
</Button.RenderTransform>
<Button.Template>
<ControlTemplate>
<Image Source="/Images\NextPage\button_begin.png"/>
</ControlTemplate>
</Button.Template>
</Button>
<Button Width="" Height="" Style="{StaticResource PageButton}" Grid.Column="" BorderThickness="" Name="btnRew" Click="btnRew_Click" Cursor="Hand">
<Button.RenderTransform>
<ScaleTransform CenterX="" CenterY="" ScaleX="" ScaleY=""/>
</Button.RenderTransform>
<Button.Template>
<ControlTemplate>
<Image Source="/Images\NextPage\button_rew.png"/>
</ControlTemplate>
</Button.Template>
</Button>
<Button Width="" Height="" Style="{StaticResource PageButton}" Grid.Column="" BorderThickness="" Name="btnFF" Click="btnFF_Click" Cursor="Hand">
<Button.RenderTransform>
<ScaleTransform CenterX="" CenterY="" ScaleX="" ScaleY=""/>
</Button.RenderTransform>
<Button.Template>
<ControlTemplate>
<Image Source="/Images\NextPage\button_ff.png"/>
</ControlTemplate>
</Button.Template>
</Button>
<Button Width="" Height="" Style="{StaticResource PageButton}" Grid.Column="" BorderThickness="" Name="btnLast" Click="btnLast_Click" Cursor="Hand">
<Button.RenderTransform>
<ScaleTransform CenterX="" CenterY="" ScaleX="" ScaleY=""/>
</Button.RenderTransform>
<Button.Template>
<ControlTemplate>
<Image Source="/Images\NextPage\button_end.png"/>
</ControlTemplate>
</Button.Template>
</Button>
<Button Width="" Height="" Style="{StaticResource PageButton}" Grid.Column="" BorderThickness="" Name="btnRefresh" Click="btnRefresh_Click" Cursor="Hand">
<Button.RenderTransform>
<ScaleTransform CenterX="" CenterY="" ScaleX="" ScaleY=""/>
</Button.RenderTransform>
<Button.Template>
<ControlTemplate>
<Image Source="/Images\NextPage\button_rotate_ccw.png"/>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
</UserControl>
NextPageControl的后台代码
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>
/// NextPageControl.xaml 的交互逻辑
/// </summary>
public partial class NextPageControl : UserControl
{
//定义一个委托
public delegate void PageChangedHandle(object sender, EventArgs e);
//定义一个事件
public event PageChangedHandle PageChanged; public NextPageControl()
{
InitializeComponent(); }
//总页数
private int totalPage = ;
/// <summary>
/// 当前页
/// </summary>
private int currentPage = ; #region 每页显示的条数
/// <summary>
/// 注册当前页
/// </summary>
public static readonly DependencyProperty PageSizeProperty = DependencyProperty.Register("PageSize", typeof(String),
typeof(NextPageControl), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsMeasure), new ValidateValueCallback(CurrentPageValidation)); /// <summary>
/// 验证当前页
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool PageSizeValidation(object value)
{
return true;
}
/// <summary>
/// 当前页
/// </summary>
public string PageSize
{
get { return GetValue(NextPageControl.PageSizeProperty).ToString(); }
set
{
SetValue(NextPageControl.PageSizeProperty, value);
lblPageSize.Content = value;
}
}
#endregion #region 当前页
/// <summary>
/// 注册当前页
/// </summary>
public static readonly DependencyProperty CurrentPageProperty = DependencyProperty.Register("CurrentPage", typeof(String),
typeof(NextPageControl), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnCurrentPageChanged)), new ValidateValueCallback(CurrentPageValidation)); /// <summary>
/// 验证当前页
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool CurrentPageValidation(object value)
{
return true;
}
/// <summary>
/// 当前页
/// </summary>
public string CurrentPage
{
get { return GetValue(NextPageControl.CurrentPageProperty).ToString(); }
set
{
SetValue(NextPageControl.CurrentPageProperty, value); lblCurrentPage.Content = value;
}
} #endregion #region 总页数
/// <summary>
/// 总页数
/// </summary>
public static readonly DependencyProperty TotalPageProperty = DependencyProperty.Register("TotalPage", typeof(String), typeof(NextPageControl), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnTotalPageChanged)), new ValidateValueCallback(TotalPageValidation)); /// <summary>
/// 总页数进行验证
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool TotalPageValidation(object value)
{
return true;
}
/// <summary>
/// 总页数
/// </summary>
public string TotalPage
{
get { return GetValue(NextPageControl.TotalPageProperty).ToString(); }
set
{
SetValue(NextPageControl.TotalPageProperty, value); }
} #endregion #region 私有方法
/// <summary>
/// 值改变方法将由此方法来引发事件
/// </summary>
private void PageChangedFunc()
{
if (PageChanged != null)
{
///引发事件
PageChanged(this, new EventArgs());
}
} #endregion /// <summary>
/// 首页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnFrist_Click(object sender, RoutedEventArgs e)
{
CurrentPage = "";
PageChangedFunc(); }
/// <summary>
/// 前一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRew_Click(object sender, RoutedEventArgs e)
{
totalPage = GetIntVal(TotalPage);
currentPage = GetIntVal(CurrentPage);
if (currentPage > )
{
currentPage = currentPage - ;
CurrentPage = currentPage.ToString();
}
PageChangedFunc();
}
/// <summary>
/// 后一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnFF_Click(object sender, RoutedEventArgs e)
{
currentPage = GetIntVal(CurrentPage);
totalPage = GetIntVal(TotalPage);
if (currentPage < totalPage)
{
currentPage = currentPage + ;
CurrentPage = currentPage.ToString();
}
PageChangedFunc();
}
//尾页
private void btnLast_Click(object sender, RoutedEventArgs e)
{
currentPage = GetIntVal(TotalPage);
CurrentPage = currentPage.ToString();
PageChangedFunc();
} /// <summary>
/// 刷新当前页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
PageChangedFunc();
} private int GetIntVal(string val)
{
int temp = ;
if (!int
.TryParse(val, out temp))
{
temp = ;
}
return temp;
}
/// <summary>
/// 当当前页值改变
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnTotalPageChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{ //MyButton hsb = (MyButton)sender;
// SetValue(NextPageControl.CurrentPageProperty, "1");
// SetFunc();
//Image image = hsb.tehImage;
//CurrentPage = "1";
//image.Source = new BitmapImage((Uri)e.NewValue);
}
/// <summary>
/// 当当前页值改变
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnCurrentPageChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{ //MyButton hsb = (MyButton)sender;
// SetValue(NextPageControl.CurrentPageProperty, "1");
// ShowMsg("event");
//Image image = hsb.tehImage;
//CurrentPage = "1";
//image.Source = new BitmapImage((Uri)e.NewValue);
} }
}
在完成分页控件以后
定义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="" Width="">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=""></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height=""></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="">
<Button Content="查询" Command="{Binding Path=QueryCommand}"/>
</StackPanel>
<DataGrid Grid.Row=""
HeadersVisibility="Column" VerticalGridLinesBrush="WhiteSmoke"
AutoGenerateColumns="False" CanUserAddRows="False" SelectionUnit="FullRow"
ItemsSource="{Binding Path=ArchiveModels,Mode=TwoWay}" >
<DataGrid.Columns>
<DataGridTextColumn Header="文件编号" Width="" IsReadOnly="True" Binding="{Binding Path=Id}"/>
<DataGridTextColumn Header="文件名称" Width="" IsReadOnly="True" Binding="{Binding Path=ArchiveName}" />
</DataGrid.Columns>
</DataGrid>
<local:NextPageControl Grid.Row="" 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 = ;
ArchiveModels = GetData(PageSize, out totalCount);
if (totalCount % PageSize == )
{
TotalPage = (totalCount / PageSize).ToString();
}
else
{
TotalPage = ((totalCount / PageSize) + ).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 = "";
/// <summary>
/// 当前页
/// </summary>
public string CurrentPage
{
get { return _currentPage; }
set
{
_currentPage = value;
RaisePropertyChanged();
}
} private int _pageSize = ;
/// <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 = ;
var data = new ObservableCollection<ArchiveModel>();
for (int i = ; i < pageSize; i++)
{
data.Add(new ArchiveModel() { Id = i + , ArchiveName = string.Format("ArchiveName{0}", i) });
}
return data;
} private ObservableCollection<ArchiveModel> QueryData(int pageIndex, int pageSize)
{
var data = new ObservableCollection<ArchiveModel>();
for (int i = ; i < pageSize; i++)
{
data.Add(new ArchiveModel() { Id = (pageIndex - ) * 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 用户控件完成分页的更多相关文章
- 浅尝辄止WPF自定义用户控件(实现颜色调制器)
主要利用用户控件实现一个自定义的颜色调制控件,实现一个小小的功能,具体实现界面如下. 首先自己新建一个wpf的用户控件类,我就放在我的wpf项目的一个文件夹下面,因为是一个很小的东西,所以就没有用mv ...
- 【WPF】WPF开发用户控件、用户控件属性依赖DependencyProperty实现双向绑定、以及自定义实现Command双向绑定功能演示
前言: Wpf开发过程中,最经常使用的功能之一,就是用户控件(UserControl)了.用户控件可以用于开发用户自己的控件进行使用,甚至可以用于打造一套属于自己的UI框架.依赖属性(Dependen ...
- 036. asp.netWeb用户控件之五使用用户控件实现分页数据导航
UserDataPager.ascx用户控件代码: <%@ Control Language="C#" AutoEventWireup="true" Co ...
- WPF 创建用户控件并引用
项目源码地址:https://github.com/lizhiqiang0204/WpfControlLibrary.git 首先创建新项目->WPF用户控件库项目 在UserControl1. ...
- WPF中用户控件对比自定义控件(UserControl VS CustomControl)
接着这篇文章(http://www.cnblogs.com/shiyue/archive/2013/02/02/2889907.html)写: 用户控件(组合) 用于在一个项目中使用多次 自定义控件( ...
- wpf创建用户控件(计时器控件)
在vs中新增用户控件 前台xaml如下代码: <UserControl x:Class="Zh.SelfServiceEquipment.UI.ZhControls.CountDown ...
- WPF自定义用户控件不显示
1,Themes\Generic.xaml最好不要更名 "Generic.xaml"这个名称并非偶然通过上面的叙述,你可能会有冲动将Generic.xaml中的Style代码剪切出 ...
- Web用户控件开发--分页控件
分页是Web应用程序中最常用到的功能之一,在ASP.NET中,虽然自带了一些可以分页的数据控件,但其分页功能并不尽如人意.本文对于这些数据控件的假分页暂且不表,如有不明白的同学请百Google度之. ...
- wpf中用户控件的属性重用
我们经常会抽取一些可重用的控件,某个属性是否需要重用,直接决定了这个属性的绑定方式. 1.完全不可重用的控件 有一些与业务强相关的控件,它们的属性完全来自ViewModel,越是相对复杂的控件,越容易 ...
随机推荐
- Spring 从零開始-03
这里说说bean装配集合.spring的支持的集合元素,其基本使用方式如同与Java的集合,所以假设对Java的集合不太了解的能够先找个帖子好好学习一下, 时间关系这里就不说了. ~~ list的样例 ...
- Newton's Method
在求最优解时,前面很多地方都用梯度下降(Gradient Descent)的方法,但由于最优步长很难确定,可能会出现总是在最优解附近徘徊的情况,致使最优解的搜索过程很缓慢.牛顿法(Newton's M ...
- Java_生产者消费者模式
/* * To change this license header, choose License Headers in Project Properties. * To change this t ...
- Android(java)学习笔记121:android.intent.action.MAIN 与 android.intent.category.LAUNCHER 理解
先看看网路上的说法: android.intent.action.MAIN决定应用程序最先启动的 Activity android.intent.category.LAUNCHER决定应用程序是否显示 ...
- Android 断点续传
断点续传指的是在下载或上传时,将下载或上传任务(一个文件或一个压缩包)人为的划分为几个部分,每一个部分采用一个线程进行上传或下载,如果碰到网络故障,可以从已经上传或下载的部分开始继续上传下载未完成的部 ...
- PowerDesigner 根据NAME属性自动生成表和列注释(不用写脚本)
PowerDesigner 11 menu: [Database]->[Database Generation] tab: [Tables & Views]->check tabl ...
- 关于automatic_Panoramic_Image_Stitching_using_Invariant_features 的阅读笔记
并没有都读完,不过感觉还是有必要做一个笔记的,毕竟这只是随笔不是文章,所以可以有多少写多少,也算是工作总结了,最重要的是这个好在可以,完成所有有意义文档的检索,比起自己的word来说高级很多~~~. ...
- 【技巧】centos6.5_yum本地安装mysql
环境:centos6.5 .64位.mysql5.6.3 有鉴于此前在网上得来的Yum换源安装mysql,成功是可以成功,就是会受网速等影响,有时候会因为yum下载rpm包很慢以致超时失败. 而且考虑 ...
- 【转载】TCL装载包和版本控制
转载来源:http://blog.chinaunix.net/uid-9967220-id-3033702.html package forget ?package package ...? ...
- [转载]ubuntu Atheros Communications Device 1083 驱动
Ubuntu 版本: Ubuntu server 10.10 在2016-03-26 上午时,拆开公司一台server电脑的CPU风扇不转,电源都烧掉了(潮湿的原因)... 在2016-03-28 打 ...