新建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;

最新文章

  1. 学习之路~sqh
  2. Activity 横竖屏切换
  3. java 线程协作 wait(等待)与 notiy(通知)
  4. chrome developer tool—— 断点调试篇
  5. IOS客户端Coding项目记录(六)
  6. django 提示ImportError: cannot import name json_response
  7. 网站Session 处理方式
  8. bind() live()和delegate 区别
  9. java网络编程基础
  10. NTFS文件系统简介(转载)
  11. BIP_开发案例08_BI Publisher图表示例 饼状图/直方图/折线图(案例)
  12. 使用libzplay库封装一个音频类
  13. TCP11种状态分析和测试
  14. JQuery调用iframe父页面元素与方法
  15. Python中什么时候使用生成器?
  16. 阿里云部署java项目参考如下链接
  17. Web打印控件Lodop实现表格物流单的打印
  18. 每周工作4小时,蒂莫西&#183;费里斯 最理想的工作方式和生活方式,QQ群666243547
  19. WPF ScrollViewer滚动条样式,适合触摸屏使用
  20. Android 开发工具类 04_KeyBoardUtils

热门文章

  1. 更改mysql数据库latin1_swedish_ci为utf8
  2. top N彻底解秘
  3. Java菜鸟学习笔记--数组篇(二):数组实例&amp;args实例
  4. 如何将下载好的jar包添加到maven本地仓库
  5. Linq to sql语法
  6. hadoop实例
  7. (转)LINUX的端口和服务
  8. 异常Address already in use: JVM_Bind的处理
  9. Android常用网址[转]
  10. cocos2d-x创建精灵动画