新建Custom Control,名:PagingDataGrid

打开工程下面的Themes\Generic.xaml

xaml里面代码替换如下

 <Style x:Key="{x:Type loc:PagingDataGrid}" TargetType="{x:Type loc:PagingDataGrid}">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="BorderBrush" Value="#FF688CAF" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="RowDetailsVisibilityMode" Value="VisibleWhenSelected" />
<Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
<Setter Property="CanUserSortColumns" Value="False"/>
<Setter Property="AlternatingRowBackground" Value="SkyBlue"/>
<Setter Property="AlternationCount" Value="2"/>
<Setter Property="ScrollViewer.PanningMode" Value="Both"/>
<Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type loc:PagingDataGrid}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True" Padding="{TemplateBinding Padding}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0" Focusable="false" Name="DG_ScrollViewer">
<ScrollViewer.Template>
<ControlTemplate TargetType="{x:Type ScrollViewer}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Button Command="ApplicationCommands.SelectAll" Focusable="False" Style="{DynamicResource {ComponentResourceKey ResourceId=DataGridSelectAllButtonStyle, TypeInTargetAssembly={x:Type DataGrid}}}" Width="{Binding CellsPanelHorizontalOffset, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type DataGrid}}}">
<Button.Visibility>
<Binding Path="HeadersVisibility" RelativeSource="{RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type DataGrid}}">
<Binding.ConverterParameter>
<DataGridHeadersVisibility>All</DataGridHeadersVisibility>
</Binding.ConverterParameter>
</Binding>
</Button.Visibility>
</Button>
<DataGridColumnHeadersPresenter x:Name="PART_ColumnHeadersPresenter" Grid.Column="1">
<DataGridColumnHeadersPresenter.Visibility>
<Binding Path="HeadersVisibility" RelativeSource="{RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type DataGrid}}">
<Binding.ConverterParameter>
<DataGridHeadersVisibility>Column</DataGridHeadersVisibility>
</Binding.ConverterParameter>
</Binding>
</DataGridColumnHeadersPresenter.Visibility>
</DataGridColumnHeadersPresenter>
<ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" CanHorizontallyScroll="False" Grid.ColumnSpan="2" CanVerticallyScroll="False" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Grid.Row="1"/>
<ScrollBar x:Name="PART_VerticalScrollBar" Grid.Column="2" Maximum="{TemplateBinding ScrollableHeight}" Orientation="Vertical" Grid.Row="1" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportHeight}"/>
<Grid Grid.Column="1" Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding NonFrozenColumnsViewportHorizontalOffset, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type DataGrid}}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ScrollBar x:Name="PART_HorizontalScrollBar" Grid.Column="1" Maximum="{TemplateBinding ScrollableWidth}" Orientation="Horizontal" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportWidth}"/>
</Grid>
</Grid>
</ControlTemplate>
</ScrollViewer.Template>
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</ScrollViewer>
<!--分页控件-->
<StackPanel Grid.Row="1" SnapsToDevicePixels="True" VerticalAlignment="Center" Visibility="{Binding IsShowPaging,RelativeSource={RelativeSource TemplatedParent},Converter={StaticResource BoolToVisibilityConverter}}" Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="13"/>
<Setter Property="Margin" Value="3,0"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="FontSize" Value="13"/>
</Style>
<Style TargetType="ComboBox">
<Setter Property="FontSize" Value="13"/>
</Style>
<Style TargetType="Button">
<Setter Property="FontSize" Value="13"/>
</Style>
</StackPanel.Resources>
<TextBlock>总计</TextBlock>
<TextBlock Foreground="Red" Text="{Binding Total,RelativeSource={RelativeSource TemplatedParent},Mode=OneWay}" />
<TextBlock>条记录 每页显示</TextBlock>
<ComboBox x:Name="PART_DispalyCount" BorderThickness="1" BorderBrush="Red" Foreground="Red" Grid.Column="0" FontSize="12" VerticalAlignment="Center" MinWidth="40" ItemsSource="{Binding PageSizeItemsSource,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}" SelectedItem="{Binding PageSize,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
<TextBlock>条 总页数</TextBlock>
<TextBlock Margin="3" Foreground="Red" Text="{Binding PageCount,RelativeSource={RelativeSource TemplatedParent},Mode=OneWay}" />
<Button x:Name="PART_PrePage" Content="上一页"/>
<TextBlock>当前页</TextBlock>
<TextBox Width="100" Foreground="Red" x:Name="PART_PageIndex" Text="{Binding PageIndex,RelativeSource={RelativeSource TemplatedParent},Mode=OneWay}" />
<TextBlock>页</TextBlock>
<Button x:Name="PART_GoTo" Content="转到页"/>
<Button x:Name="PART_NextPage" Content="下一页"/>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsGrouping" Value="true">
<Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
</Trigger>
</Style.Triggers>
</Style>

打开PagingDataGrid.cs文件

代码如下:

 public class PagingDataGrid : DataGrid
{
static PagingDataGrid()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PagingDataGrid), new FrameworkPropertyMetadata(typeof(PagingDataGrid)));
} #region 变量定义
ComboBox PART_DispalyCount;
Button PART_PrePage;
Button PART_NextPage;
Button PART_GoTo;
TextBox PART_PageIndex;
#endregion #region 事件代理 public delegate void PagingChangedEventHandler(object sender, PagingChangedEventArgs e); public event PagingChangedEventHandler PagingChanged; private void OnPagingChanged()
{
if (PagingChanged != null)
{
PagingChanged(this, new PagingChangedEventArgs() { PageIndex = PageIndex, PageSize = PageSize });
}
}
#endregion #region 一般属性
private List<Student> dataItems = new List<Student>(); public List<Student> DataItems
{
get
{
return dataItems;
}
set
{
dataItems = value;
ReCalcLayout();
}
} List<int> list = new List<int>(); public List<int> PageSizeItemsSource
{
get
{
return list;
}
set
{
list = value;
}
}
#endregion #region 依赖属性
/// <summary>
/// 页大小
/// </summary>
public int PageSize
{
get { return (int)GetValue(PageSizeProperty); }
set { SetValue(PageSizeProperty, value); }
} /// <summary>
/// 当前页
/// </summary>
public int PageIndex
{
get { return (int)GetValue(PageIndexProperty); }
set { SetValue(PageIndexProperty, value); }
} /// <summary>
/// 总计录数
/// </summary>
public int Total
{
get { return (int)GetValue(TotalProperty); }
set { SetValue(TotalProperty, value); }
} /// <summary>
/// 是否显示页
/// </summary>
public bool IsShowPaging
{
get { return (bool)GetValue(IsShowPagingProperty); }
set { SetValue(IsShowPagingProperty, value); }
} /// <summary>
/// 总页数
/// </summary>
public int PageCount
{
get { return (int)GetValue(PageCountProperty); }
set { SetValue(PageCountProperty, value); }
} // Using a DependencyProperty as the backing store for PageCount. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PageCountProperty =
DependencyProperty.Register("PageCount", typeof(int), typeof(PagingDataGrid), new UIPropertyMetadata()); // Using a DependencyProperty as the backing store for End. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EndProperty =
DependencyProperty.Register("End", typeof(int), typeof(PagingDataGrid), new UIPropertyMetadata()); // Using a DependencyProperty as the backing store for Start. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StartProperty =
DependencyProperty.Register("Start", typeof(int), typeof(PagingDataGrid), new UIPropertyMetadata()); // Using a DependencyProperty as the backing store for IsShowPaging. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsShowPagingProperty =
DependencyProperty.Register("IsShowPaging", typeof(bool), typeof(PagingDataGrid), new UIPropertyMetadata(true)); // Using a DependencyProperty as the backing store for Total. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TotalProperty =
DependencyProperty.Register("Total", typeof(int), typeof(PagingDataGrid), new UIPropertyMetadata()); // Using a DependencyProperty as the backing store for PageIndex. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PageIndexProperty =
DependencyProperty.Register("PageIndex", typeof(int), typeof(PagingDataGrid), new UIPropertyMetadata()); // Using a DependencyProperty as the backing store for PageSize. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PageSizeProperty =
DependencyProperty.Register("PageSize", typeof(int), typeof(PagingDataGrid), new UIPropertyMetadata()); #endregion #region 相关命令
RoutedCommand NextPageCommand = new RoutedCommand();
RoutedCommand PrePageCommand = new RoutedCommand();
RoutedCommand GoToCommand = new RoutedCommand();
#endregion #region 重写方法
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
//获取模板中的控件
PART_DispalyCount = GetTemplateChild("PART_DispalyCount") as ComboBox;
PART_PrePage = GetTemplateChild("PART_PrePage") as Button;
PART_NextPage = GetTemplateChild("PART_NextPage") as Button;
PART_GoTo = GetTemplateChild("PART_GoTo") as Button;
PART_PageIndex = GetTemplateChild("PART_PageIndex") as TextBox;
//添加控件命令Binding
PART_NextPage.CommandBindings.Add(new CommandBinding(NextPageCommand, NextPage_Excuted, NextPage_CanExcuted));
PART_PrePage.CommandBindings.Add(new CommandBinding(PrePageCommand, PrePage_Excuted, PrePage_CanExcuted));
PART_GoTo.CommandBindings.Add(new CommandBinding(GoToCommand, GoTo_Excuted, GoTo_CanExcuted));
PART_NextPage.Command = NextPageCommand;
PART_PrePage.Command = PrePageCommand;
PART_GoTo.Command = GoToCommand;
//添加控件事件
PART_DispalyCount.SelectionChanged += PART_DispalyCount_SelectionChanged;
} private void GoTo_Excuted(object sender, ExecutedRoutedEventArgs e)
{
int idx = ;
if (int.TryParse(PART_PageIndex.Text, out idx))
{
GoTo(idx);
}
} private void GoTo_CanExcuted(object sender, CanExecuteRoutedEventArgs e)
{
int idx = ;
if (int.TryParse(PART_PageIndex.Text, out idx))
{
if (idx > PageCount || idx <= )
{
e.CanExecute = false;
}
else
{
e.CanExecute = true;
}
}
else
{
e.CanExecute = false;
}
} private void NextPage_CanExcuted(object sender, CanExecuteRoutedEventArgs e)
{
if (PageIndex == PageCount)
{
e.CanExecute = false;
}
else
{
e.CanExecute = true;
}
} private void NextPage_Excuted(object sender, ExecutedRoutedEventArgs e)
{
GoTo(PageIndex++);
} private void PrePage_CanExcuted(object sender, CanExecuteRoutedEventArgs e)
{
if (PageIndex == )
{
e.CanExecute = false;
}
else
{
e.CanExecute = true;
}
} private void PrePage_Excuted(object sender, ExecutedRoutedEventArgs e)
{
GoTo(PageIndex--);
}
#endregion #region 分页事件
void PART_DispalyCount_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
PageSize = int.Parse((sender as ComboBox).SelectedItem.ToString());
ReCalcLayout();
GoTo(PageIndex);
} private void GoTo(int page)
{
ItemsSource = DataItems.Skip((PageIndex - ) * PageSize).Take(PageSize).ToList();
} private void ReCalcLayout()
{
Total = DataItems.Count;
int pc = Total / PageSize;
if (Total % PageSize == )
{
PageCount = pc;
}
else
{
PageCount = pc + ;
}
PageIndex = PageIndex > PageCount ? PageCount : PageIndex;
}
#endregion
}

此外还需要一个类支持PagingChangedEventArgs

 /// <summary>
/// 页跳转参数
/// </summary>
public class PagingChangedEventArgs : EventArgs
{
public int PageSize { get; set; }
public int PageIndex { get; set; }
}

控件完成,调试:

 <local:PagingDataGrid x:Name="pdg" PagingChanged="pdg_PagingChanged" IsShowPaging="True" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True" SnapsToDevicePixels="True" CanUserReorderColumns="False">
<local:PagingDataGrid.PageSizeItemsSource>
<sys:Int32>5</sys:Int32>
<sys:Int32>10</sys:Int32>
<sys:Int32>15</sys:Int32>
<sys:Int32>20</sys:Int32>
<sys:Int32>30</sys:Int32>
<sys:Int32>50</sys:Int32>
<sys:Int32>100</sys:Int32>
</local:PagingDataGrid.PageSizeItemsSource>
<local:PagingDataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="AAA"/>
<DataGridTextColumn Binding="{Binding Age}" Header="BBB"/>
<DataGridTextColumn Binding="{Binding Sex}" Width="*" Header="CCC"/>
</local:PagingDataGrid.Columns>
</local:PagingDataGrid>

新建调试类Student

     public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string MoreInfo { get; set; }
}

调试代码,注意这里使用DataItems保存信息,如果使用Items或是ItemsSource则无分页效果

 List<Student> list = new List<Student>();
for (int i = ; i < ; i++)
{
list.Add(new Student() { Name = Guid.NewGuid().ToString(), Age = i, MoreInfo = "Sex" });
}
pdg.DataItems = list;

WPF自定义DataGrid分页控件的更多相关文章

  1. WPF里DataGrid分页控件

    1.主要代码: using System; using System.Collections.ObjectModel; using System.Windows; using System.Windo ...

  2. WPF自定义选择年月控件详解

    本文实例为大家分享了WPF自定义选择年月控件的具体代码,供大家参考,具体内容如下 封装了一个选择年月的控件,XAML代码: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...

  3. 自定义angularjs分页控件

    继昨天写了knockoutjs+ jquery pagination+asp.net web Api 实现无刷新列表页 ,正好最近刚学习angularjs ,故琢磨着写一个angularjs版本的分页 ...

  4. [转]Oracle分页之二:自定义web分页控件的封装

    本文转自:http://www.cnblogs.com/scy251147/archive/2011/04/16/2018326.html 上节中,讲述的就是Oracle存储过程分页的使用方式,但是如 ...

  5. C# WinForm自定义通用分页控件

    大家好,前几天因工作需要要开发一个基于WinForm的小程序.其中要用到分页,最开始的想法找个第三方的dll用一下,但是后来想了想觉得不如自己写一个玩一下 之前的web开发中有各式各样的列表组件基本都 ...

  6. WPF简单的分页控件实现

    XAML代码(使用ItemsControl控件实现): <UserControl x:Class="SunCreate.Vipf.Client.UI.CityDoor.PageCont ...

  7. WPF 自定义DateControl DateTime控件

    自定义日期控件,月份选择.如下是日期的一些效果图. 具体的样式.颜色可以根据下面的代码,自己调节即可    1.日期控件的界面 <UserControl x:Class="WpfApp ...

  8. WPF 自定义DateControl DateTime控件(转)

    自定义日期控件,月份选择.如下是日期的一些效果图. 具体的样式.颜色可以根据下面的代码,自己调节即可    1.日期控件的界面 <UserControl x:Class="WpfApp ...

  9. WPF自定义数字输入框控件

    要求:只能输入数字和小数点,可以设置最大值,最小值,小数点前长度,小数点后长度(支持绑定设置): 代码如下: using System; using System.Collections.Generi ...

随机推荐

  1. ipython notebook使用教程

    在一次师兄(师兄博客地址)的例会汇报中,介绍了ipython notebook,当时觉得很酷炫,渐渐自己使用的时候才发现真的很强大.抽空整理下,找了些资料进行补充,并挨个进行了实现,留个笔记,也欢迎喜 ...

  2. UVA 11178 Morley's Theorem(旋转+直线交点)

    题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=18543 [思路] 旋转+直线交点 第一个计算几何题,照着书上代码打 ...

  3. [转]让程序在崩溃时体面的退出之SEH+Dump文件

    原文地址:http://blog.csdn.net/starlee/article/details/6649605 在我上篇文章<让程序在崩溃时体面的退出之SEH>中讲解了SEH中try/ ...

  4. 《University Calculus》-chape8-无穷序列和无穷级数-基本极限恒等式

    基于基本的极限分析方法(诸多的无穷小以及洛必达法则),我们能够得到推导出一些表面上看不是那么显然的式子,这些极限恒等式往往会在其他的推导过程中用到,其中一个例子就是概率论中的极限定理那部分知识.

  5. 5 kafka整合storm

    本博文的主要内容有 .kafka整合storm   .storm-kafka工程  .storm + kafka的具体应用场景有哪些? 要想kafka整合storm,则必须要把这个storm-kafk ...

  6. TFS(Team Foundation Server)介绍和入门

    在本文的两个部分中,我将介绍Team Foundation Server的一些核心特征,重点介绍在本产品的日常应用中是怎样将这些特性结合在一起使用的. 作为一名软件开发者,在我的职业生涯中,我常常会用 ...

  7. HDU3336-Count the string(KMP)

    Count the string Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  8. SunDay天气——开放源代码

    前段时间也些小忙,一直没有时间去弄Github,所以源代码一直没有放出来. 本周末特抽了些时间出来,熟悉了下Github,并把源代码给弄了去.欢迎大牛重吐槽.指导...... 费话不多说,上图. 近期 ...

  9. android 24 设置与桌面相同的action和category

    设置与桌面相同的action和category 安卓系统桌面也是一个activity,安卓桌面的action和category是: <activity android:name="co ...

  10. linux 管道--转

    linux 管道 管道是Linux中很重要的一种通信方式,是把一个程序的输出直接连接到另一个程序的输入,常说的管道多是指无名管道,无名管道只能用于具有亲缘关系的进程之间,这是它与有名管道的最大区别. ...