项目中经常会有分页查询的情况,在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