[C.C++] WPF实现列表分页控件的示例代码

701 0
王子 2022-11-5 08:15:11 | 显示全部楼层 |阅读模式
WPF 之列表分页控件
框架使用大于等于.NET40。
Visual Studio 2022。
项目使用 MIT 开源许可协议。
新建Pagination自定义控件继承自Control。
正常模式分页 在外部套Grid分为0 - 5列:
    Grid.Column 0 总页数共多少300条。Grid.Column 1 输入每页显示多少10条。Grid.Column 2 上一页按钮。Grid.Column 3 所有页码按钮此处使用ListBox。Grid.Column 4 下一页按钮。Grid.Column 5 跳转页1码输入框。
精简模式分页 在外部套Grid分为0 - 9列:
    Grid.Column 0 总页数共多少300条。Grid.Column 2 输入每页显示多少10条。Grid.Column 3 条 / 页。Grid.Column 5 上一页按钮。Grid.Column 7 跳转页1码输入框。Grid.Column 9 下一页按钮。
每页显示与跳转页码数控制只允许输入数字,不允许粘贴。
实现代码
  1. <ColumnDefinitionWidth="Auto"/>
  2. <ColumnDefinitionWidth="10"/>
  3. <ColumnDefinitionWidth="Auto/>
  4. <ColumnDefinitionWidth="Auto"/>
  5. <ColumnDefinitionWidth="10"/>
  6. <ColumnDefinitionWidth="Auto"/>
  7. <ColumnDefinitionWidth="5"/>
  8. <ColumnDefinitionWidth="Auto"/>
  9. <ColumnDefinitionWidth="5"/>
  10. <ColumnDefinitionWidth="Auto"/>
复制代码


1) Pagination.cs 如下:
  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Windows;
  5. usingSystem.Windows.Controls;
  6. usingSystem.Windows.Input;
  7. usingWPFDevelopers.Helpers;
  8. namespaceWPFDevelopers.Controls
  9. {
  10. [TemplatePart(Name=CountPerPageTextBoxTemplateName,Type=typeof(TextBox))]
  11. [TemplatePart(Name=JustPageTextBoxTemplateName,Type=typeof(TextBox))]
  12. [TemplatePart(Name=ListBoxTemplateName,Type=typeof(ListBox))]
  13. publicclassPagination:Control
  14. {
  15. privateconststringCountPerPageTextBoxTemplateName="PART_CountPerPageTextBox";
  16. privateconststringJustPageTextBoxTemplateName="PART_JumpPageTextBox";
  17. privateconststringListBoxTemplateName="PART_ListBox";
  18. privateconststringEllipsis="···";
  19. privatestaticreadonlyType_typeofSelf=typeof(Pagination);
  20. privateTextBox_countPerPageTextBox;
  21. privateTextBox_jumpPageTextBox;
  22. privateListBox_listBox;
  23. staticPagination()
  24. {
  25. InitializeCommands();
  26. DefaultStyleKeyProperty.OverrideMetadata(_typeofSelf,newFrameworkPropertyMetadata(_typeofSelf));
  27. }
  28. #regionOverride
  29. publicoverridevoidOnApplyTemplate()
  30. {
  31. base.OnApplyTemplate();
  32. UnsubscribeEvents();
  33. _countPerPageTextBox=GetTemplateChild(CountPerPageTextBoxTemplateName)asTextBox;
  34. if(_countPerPageTextBox!=null)
  35. {
  36. _countPerPageTextBox.ContextMenu=null;
  37. _countPerPageTextBox.PreviewTextInput+=_countPerPageTextBox_PreviewTextInput;
  38. _countPerPageTextBox.PreviewKeyDown+=_countPerPageTextBox_PreviewKeyDown;
  39. }
  40. _jumpPageTextBox=GetTemplateChild(JustPageTextBoxTemplateName)asTextBox;
  41. if(_jumpPageTextBox!=null)
  42. {
  43. _jumpPageTextBox.ContextMenu=null;
  44. _jumpPageTextBox.PreviewTextInput+=_countPerPageTextBox_PreviewTextInput;
  45. _jumpPageTextBox.PreviewKeyDown+=_countPerPageTextBox_PreviewKeyDown;
  46. }
  47. _listBox=GetTemplateChild(ListBoxTemplateName)asListBox;
  48. Init();
  49. SubscribeEvents();
  50. }
  51. privatevoid_countPerPageTextBox_PreviewKeyDown(objectsender,KeyEventArgse)
  52. {
  53. if(Key.Space==e.Key
  54. ||
  55. Key.V==e.Key
  56. &&e.KeyboardDevice.Modifiers==ModifierKeys.Control)
  57. e.Handled=true;
  58. }
  59. privatevoid_countPerPageTextBox_PreviewTextInput(objectsender,TextCompositionEventArgse)
  60. {
  61. e.Handled=ControlsHelper.IsNumber(e.Text);
  62. }
  63. #endregion
  64. #regionCommand
  65. privatestaticvoidInitializeCommands()
  66. {
  67. PrevCommand=newRoutedCommand("Prev",_typeofSelf);
  68. NextCommand=newRoutedCommand("Next",_typeofSelf);
  69. CommandManager.RegisterClassCommandBinding(_typeofSelf,
  70. newCommandBinding(PrevCommand,OnPrevCommand,OnCanPrevCommand));
  71. CommandManager.RegisterClassCommandBinding(_typeofSelf,
  72. newCommandBinding(NextCommand,OnNextCommand,OnCanNextCommand));
  73. }
  74. publicstaticRoutedCommandPrevCommand{get;privateset;}
  75. publicstaticRoutedCommandNextCommand{get;privateset;}
  76. privatestaticvoidOnPrevCommand(objectsender,RoutedEventArgse)
  77. {
  78. varctrl=senderasPagination;
  79. ctrl.Current--;
  80. }
  81. privatestaticvoidOnCanPrevCommand(objectsender,CanExecuteRoutedEventArgse)
  82. {
  83. varctrl=senderasPagination;
  84. e.CanExecute=ctrl.Current>1;
  85. }
  86. privatestaticvoidOnNextCommand(objectsender,RoutedEventArgse)
  87. {
  88. varctrl=senderasPagination;
  89. ctrl.Current++;
  90. }
  91. privatestaticvoidOnCanNextCommand(objectsender,CanExecuteRoutedEventArgse)
  92. {
  93. varctrl=senderasPagination;
  94. e.CanExecute=ctrl.Current<ctrl.PageCount;
  95. }
  96. #endregion
  97. #regionProperties
  98. privatestaticreadonlyDependencyPropertyKeyPagesPropertyKey=
  99. DependencyProperty.RegisterReadOnly("Pages",typeof(IEnumerable<string>),_typeofSelf,
  100. newPropertyMetadata(null));
  101. publicstaticreadonlyDependencyPropertyPagesProperty=PagesPropertyKey.DependencyProperty;
  102. publicIEnumerable<string>Pages=>(IEnumerable<string>)GetValue(PagesProperty);
  103. privatestaticreadonlyDependencyPropertyKeyPageCountPropertyKey=
  104. DependencyProperty.RegisterReadOnly("PageCount",typeof(int),_typeofSelf,
  105. newPropertyMetadata(1,OnPageCountPropertyChanged));
  106. publicstaticreadonlyDependencyPropertyPageCountProperty=PageCountPropertyKey.DependencyProperty;
  107. publicintPageCount=>(int)GetValue(PageCountProperty);
  108. privatestaticvoidOnPageCountPropertyChanged(DependencyObjectd,DependencyPropertyChangedEventArgse)
  109. {
  110. varctrl=dasPagination;
  111. varpageCount=(int)e.NewValue;
  112. /*
  113. if(ctrl._jumpPageTextBox!=null)
  114. ctrl._jumpPageTextBox.Maximum=pageCount;
  115. */
  116. }
  117. publicstaticreadonlyDependencyPropertyIsLiteProperty=
  118. DependencyProperty.Register("IsLite",typeof(bool),_typeofSelf,newPropertyMetadata(false));
  119. publicboolIsLite
  120. {
  121. get=>(bool)GetValue(IsLiteProperty);
  122. set=>SetValue(IsLiteProperty,value);
  123. }
  124. publicstaticreadonlyDependencyPropertyCountProperty=DependencyProperty.Register("Count",typeof(int),
  125. _typeofSelf,newPropertyMetadata(0,OnCountPropertyChanged,CoerceCount));
  126. publicintCount
  127. {
  128. get=>(int)GetValue(CountProperty);
  129. set=>SetValue(CountProperty,value);
  130. }
  131. privatestaticobjectCoerceCount(DependencyObjectd,objectvalue)
  132. {
  133. varcount=(int)value;
  134. returnMath.Max(count,0);
  135. }
  136. privatestaticvoidOnCountPropertyChanged(DependencyObjectd,DependencyPropertyChangedEventArgse)
  137. {
  138. varctrl=dasPagination;
  139. varcount=(int)e.NewValue;
  140. ctrl.SetValue(PageCountPropertyKey,(int)Math.Ceiling(count*1.0/ctrl.CountPerPage));
  141. ctrl.UpdatePages();
  142. }
  143. publicstaticreadonlyDependencyPropertyCountPerPageProperty=DependencyProperty.Register("CountPerPage",
  144. typeof(int),_typeofSelf,newPropertyMetadata(50,OnCountPerPagePropertyChanged,CoerceCountPerPage));
  145. publicintCountPerPage
  146. {
  147. get=>(int)GetValue(CountPerPageProperty);
  148. set=>SetValue(CountPerPageProperty,value);
  149. }
  150. privatestaticobjectCoerceCountPerPage(DependencyObjectd,objectvalue)
  151. {
  152. varcountPerPage=(int)value;
  153. returnMath.Max(countPerPage,1);
  154. }
  155. privatestaticvoidOnCountPerPagePropertyChanged(DependencyObjectd,DependencyPropertyChangedEventArgse)
  156. {
  157. varctrl=dasPaginatio;
  158. varcountPerPage=(int)e.NewValue;
  159. if(ctrl._countPerPageTextBox!=null)
  160. ctrl._countPerPageTextBox.Text=countPerPage.ToString();
  161. ctrl.SetValue(PageCountPropertyKey,(int)Math.Ceiling(ctrl.Count*1.0/countPerPage));
  162. if(ctrl.Current!=1)
  163. ctrl.Current=1;
  164. else
  165. ctrl.UpdatePages();
  166. }
  167. publicstaticreadonlyDependencyPropertyCurrentProperty=DependencyProperty.Register("Current",typeof(int),
  168. _typeofSelf,newPropertyMetadata(1,OnCurrentPropertyChanged,CoerceCurrent));
  169. publicintCurrent
  170. {
  171. get=>(int)GetValue(CurrentProperty);
  172. set=>SetValue(CurrentProperty,value);
  173. }
  174. privatestaticobjectCoerceCurrent(DependencyObjectd,objectvalue)
  175. {
  176. varcurrent=(int)value;
  177. varctrl=dasPagination;
  178. returnMath.Max(current,1);
  179. }
  180. privatestaticvoidOnCurrentPropertyChanged(DependencyObjectd,DependencyPropertyChangedEventArgse)
  181. {
  182. varctrl=dasPagination;
  183. varcurrent=(int)e.NewValue;
  184. if(ctrl._listBox!=null)
  185. ctrl._listBox.SelectedItem=current.ToString();
  186. if(ctrl._jumpPageTextBox!=null)
  187. ctrl._jumpPageTextBox.Text=current.ToString();
  188. ctrl.UpdatePages();
  189. }
  190. #endregion
  191. #regionEvent
  192. ///<summary>
  193. ///分页
  194. ///</summary>
  195. privatevoidOnCountPerPageTextBoxChanged(objectsender,TextChangedEventArgse)
  196. {
  197. if(int.TryParse(_countPerPageTextBox.Text,outvar_ountPerPage))
  198. CountPerPage=_ountPerPage;
  199. }
  200. ///<summary>
  201. ///跳转页
  202. ///</summary>
  203. privatevoidOnJumpPageTextBoxChanged(objectsender,TextChangedEventArgse)
  204. {
  205. if(int.TryParse(_jumpPageTextBox.Text,outvar_current))
  206. Current=_current;
  207. }
  208. ///<summary>
  209. ///选择页
  210. ///</summary>
  211. privatevoidOnSelectionChanged(objectsender,SelectionChangedEventArgse)
  212. {
  213. if(_listBox.SelectedItem==null)
  214. return;
  215. Current=int.Parse(_listBox.SelectedItem.ToString());
  216. }
  217. #endregion
  218. #regionPrivate
  219. privatevoidInit()
  220. {
  221. SetValue(PageCountPropertyKey,(int)Math.Ceiling(Count*1.0/CountPerPage));
  222. _jumpPageTextBox.Text=Current.ToString();
  223. //_jumpPageTextBox.Maximum=PageCount;
  224. _countPerPageTextBox.Text=CountPerPage.ToString();
  225. if(_listBox!=null)
  226. _listBox.SelectedItem=Current.ToString();
  227. }
  228. privatevoidUnsubscribeEvents()
  229. {
  230. if(_countPerPageTextBox!=null)
  231. _countPerPageTextBox.TextChanged-=OnCountPerPageTextBoxChanged;
  232. if(_jumpPageTextBox!=null)
  233. _jumpPageTextBox.TextChanged-=OnJumpPageTextBoxChanged;
  234. if(_listBox!=null)
  235. _listBox.SelectionChanged-=OnSelectionChanged;
  236. }
  237. privatevoidSubscribeEvents()
  238. {
  239. if(_countPerPageTextBox!=null)
  240. _countPerPageTextBox.TextChanged+=OnCountPerPageTextBoxChanged;
  241. if(_jumpPageTextBox!=null)
  242. _jumpPageTextBox.TextChanged+=OnJumpPageTextBoxChanged;
  243. if(_listBox!=null)
  244. _listBox.SelectionChanged+=OnSelectionChanged;
  245. }
  246. privatevoidUpdatePages()
  247. {
  248. SetValue(PagesPropertyKey,GetPagers(Count,Current));
  249. if(_listBox!=null&&_listBox.SelectedItem==null)
  250. _listBox.SelectedItem=Current.ToString();
  251. }
  252. privateIEnumerable<string>GetPagers(intcount,intcurrent)
  253. {
  254. if(count==0)
  255. returnnull;
  256. if(PageCount<=7)
  257. returnEnumerable.Range(1,PageCount).Select(p=>p.ToString()).ToArray();
  258. if(current<=4)
  259. returnnew[]{"1","2","3","4","5",Ellipsis,PageCount.ToString()};
  260. if(current>=PageCount-3)
  261. returnnew[]
  262. {
  263. "1",Ellipsis,(PageCount-4).ToString(),(PageCount-3).ToString(),(PageCount-2).ToString(),
  264. (PageCount-1).ToString(),PageCount.ToString()
  265. };
  266. returnnew[]
  267. {
  268. "1",Ellipsis,(current-1).ToString(),current.ToString(),(current+1).ToString(),Ellipsis,
  269. PageCount.ToString()
  270. };
  271. }
  272. #endregion
  273. }
  274. }
复制代码
2) Pagination.xaml 如下:
  1. <ResourceDictionaryxmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  2. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  3. xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
  4. xmlns:helpers="clr-namespace:WPFDevelopers.Helpers"
  5. xmlns:controls="clr-namespace:WPFDevelopers.Controls">
  6. <ResourceDictionary.MergedDictionaries>
  7. <ResourceDictionarySource="Basic/ControlBasic.xaml"/>
  8. </ResourceDictionary.MergedDictionaries>
  9. <Stylex:Key="PageListBoxStyleKey"TargetType="{x:TypeListBox}"
  10. BasedOn="{StaticResourceControlBasicStyle}">
  11. <SetterProperty="Background"Value="Transparent"/>
  12. <SetterProperty="BorderThickness"Value="0"/>
  13. <SetterProperty="Padding"Value="0"/>
  14. <SetterProperty="Template">
  15. <Setter.Value>
  16. <ControlTemplateTargetType="{x:TypeListBox}">
  17. <BorderBorderBrush="{TemplateBindingBorderBrush}"
  18. BorderThickness="{TemplateBindingBorderThickness}"
  19. Background="{TemplateBindingBackground}"
  20. SnapsToDevicePixels="True">
  21. <ScrollViewerFocusable="False"Padding="{TemplateBindingPadding}">
  22. <ItemsPresenterSnapsToDevicePixels="{TemplateBindingSnapsToDevicePixels}"/>
  23. </ScrollViewer>
  24. </Border>
  25. <ControlTemplate.Triggers>
  26. <TriggerProperty="IsGrouping"Value="True">
  27. <SetterProperty="ScrollViewer.CanContentScroll"Value="False"/>
  28. </Trigger>
  29. </ControlTemplate.Triggers>
  30. </ControlTemplate>
  31. </Setter.Value>
  32. </Setter>
  33. </Style>
  34. <Stylex:Key="PageListBoxItemStyleKey"
  35. TargetType="{x:TypeListBoxItem}"
  36. BasedOn="{StaticResourceControlBasicStyle}">
  37. <SetterProperty="MinWidth"Value="32"/>
  38. <SetterProperty="Cursor"Value="Hand"/>
  39. <SetterProperty="HorizontalContentAlignment"Value="Center"/>
  40. <SetterProperty="VerticalContentAlignment"Value="Center"/>
  41. <SetterProperty="helpers:ElementHelper.CornerRadius"Value="3"/>
  42. <SetterProperty="BorderThickness"Value="1"/>
  43. <SetterProperty="Padding"Value="5,0"/>
  44. <SetterProperty="Margin"Value="3,0"/>
  45. <SetterProperty="Background"Value="{DynamicResourceBackgroundSolidColorBrush}"/>
  46. <SetterProperty="BorderBrush"Value="{DynamicResourceBaseSolidColorBrush}"/>
  47. <SetterPoperty="Template">
  48. <Setter.Value>
  49. <ControlTemplateTargetType="{x:TypeListBoxItem}">
  50. <BorderSnapsToDevicePixels="True"
  51. Background="{TemplateBindingBackground}"
  52. BorderThickness="{TemplateBindingBorderThickness}"
  53. BorderBrush="{TemplateBindingBorderBrush}"
  54. Padding="{TemplateBindingPadding}"
  55. CornerRadius="{BindingPath=(helpers:ElementHelper.CornerRadius),RelativeSource={RelativeSourceTemplatedParent}}">
  56. <ContentPresenterx:Name="PART_ContentPresenter"
  57. HorizontalAlignment="{TemplateBindingHorizontalContentAlignment}"
  58. VerticalAlignment="{TemplateBindingVerticalContentAlignment}"
  59. RecognizesAccessKey="True"
  60. TextElement.Foreground="{TemplateBindingForeground}"/>
  61. </Border>
  62. </ControlTemplate>
  63. </Setter.Value>
  64. </Setter>
  65. <Style.Triggers>
  66. <DataTriggerBinding="{Binding.}"Value="···">
  67. <SetterProperty="IsEnabled"Value="False"/>
  68. <SetterProperty="FontWeight"Value="Bold"/>
  69. </DataTrigger>
  70. <TriggerProperty="IsMouseOver"Value="True">
  71. <SetterProperty="BorderBrush"Value="{DynamicResourceDefaultBorderBrushSolidColorBrush}"/>
  72. <SetterProperty="Background"Value="{DynamicResourceDefaultBackgroundSolidColorBrush}"/>
  73. <SetterProperty="Foreground"Value="{DynamicResourcePrimaryNormalSolidColorBrush}"/>
  74. </Trigger>
  75. <TriggerProperty="IsSelected"Value="True">
  76. <SetterProperty="Background"Value="{DynamicResourcePrimaryPressedSolidColorBrush}"/>
  77. <SetterProperty="TextElement.Foreground"Value="{DynamicResourceWindowForegroundColorBrush}"/>
  78. </Trigger>
  79. </Style.Triggers>
  80. </Style>
  81. <ControlTemplatex:Key="LitePagerControlTemplate"TargetType="{x:Typecontrols:Pagination}">
  82. <BorderBackground="{TemplateBindingBackground}"
  83. BorderBrush="{TemplateBindingBorderBrush}"
  84. BorderThickness="{TemplateBindingBorderThickness}"
  85. Padding="{TemplateBindingPadding}">
  86. <Grid>
  87. <Grid.ColumnDefinitions>
  88. <ColumnDefinitionWidth="Auto"/>
  89. <ColumnDefinitionWidth="10"/>
  90. <ColumnDefinitionWidth="Auto"/>
  91. <ColumnDefinitionWidth="Auto"/>
  92. <ColumnDefinitionWidth="10"/>
  93. <ColumnDefinitionWidth="Auto"/>
  94. <ColumnDefinitionWidth="5"/>
  95. <ColumnDefinitionWidth="Auto"/>
  96. <ColumnDefinitionWidth="5"/>
  97. <ColumnDefinitionWidth="Auto"/>
  98. </Grid.ColumnDefinitions>
  99. <TextBlockVerticalAlignment="Center"
  100. Text="{BindingCount,StringFormat=共{0}条,RelativeSource={RelativeSourceTemplatedParent}}"/>
  101. <TextBoxGrid.Column="2"x:Name="PART_CountPerPageTextBox"
  102. TextAlignment="Center"VerticalContentAlignment="Center"
  103. Width="60"MinWidth="0"
  104. input:InputMethod.IsInputMethodEnabled="False"/>
  105. <TextBlockGrid.Column="3"Text="条/页"VerticalAlignment="Center"/>
  106. <ButtonGrid.Column="5"
  107. Command="{x:Staticcontrols:Pagination.PrevCommand}">
  108. <PathWidth="7"Height="10"Stretch="Fill"
  109. Fill="{BindingForeground,RelativeSource={RelativeSourceAncestorType=Button}}"
  110. Data="{StaticResourcePathPrevious}"/>
  111. </Button>
  112. <TextBoxGrid.Column="7"x:Name="PART_JumpPageTextBox"
  113. TextAlignment="Center"
  114. VerticalContentAlignment="Center"
  115. Width="60"MinWidth="0">
  116. <TextBox.ToolTip>
  117. <TextBlock>
  118. <TextBlock.Text>
  119. <MultiBindingStringFormat="{}{0}/{1}">
  120. <BindingPath="Current"RelativeSource="{RelativeSourceTemplatedParent}"/>
  121. <BindingPath="PageCount"RelativeSource="{RelativeSourceTemplatedParent}"/>
  122. </MultiBinding>
  123. </TextBlock.Text>
  124. </TextBlock>
  125. </TextBox.ToolTip>
  126. </TextBox>
  127. <ButtonGrid.Column="9"
  128. Command="{x:Staticcontrols:Pagination.NextCommand}">
  129. <PathWidth="7"Height="10"Stretch="Fill"
  130. Fill="{BindingForeground,RelativeSource={RelativeSourceAncestorType=Button}}"
  131. Data="{StaticResourcePathNext}"/>
  132. </Button>
  133. </Grid>
  134. </Border>
  135. </ControlTemplate>
  136. <StyleTargetType="{x:Typecontrols:Pagination}"
  137. BasedOn="{StaticResourceControlBasicStyle}">
  138. <SetterProperty="Template">
  139. <Setter.Value>
  140. <ControlTemplateTargetType="{x:Typecontrols:Pagination}">
  141. <BorderBackground="{TemplateBindingBackground}"
  142. BorderBrush="{TemplateBindingBorderBrush}"
  143. BorderThickness="{TemplateBindingBorderThickness}"
  144. Padding="{TemplateBindingPadding}">
  145. <Grid>
  146. <Grid.ColumnDefinitions>
  147. <ColumnDefinitionWidth="Auto"/>
  148. <ColumnDefinitionWidth="Auto"/>
  149. <ColumnDefinitionWidth="Auto"/>
  150. <ColumnDefinitionWidth="*"/>
  151. <ColumnDefinitionWidth="Auto"/>
  152. <ColumnDefinitionWidth="Auto"/>
  153. </Grid.ColumnDefinitions>
  154. <TextBlockMargin="0,0,15,0"VerticalAlignment="Center"
  155. Text="{BindingCount,StringFormat=共{0}条,RelativeSource={RelativeSourceTemplatedParent}}"/>
  156. <StackPanelGrid.Column="1"Orientation="Horizontal"Margin="0,0,15,0">
  157. <TextBlockText="每页"VerticalAlignment="Center"/>
  158. <TextBoxx:Name="PART_CountPerPageTextBox"
  159. TextAlignment="Center"Width="60"
  160. MinWidth="0"VerticalContentAlignment="Center"
  161. FontSize="{TemplateBindingFontSize}"
  162. input:InputMethod.IsInputMethodEnabled="False"/>
  163. <TextBlockText="条"VerticalAlignment="Center"/>
  164. </StackPanel>
  165. <ButtonGrid.Column="2"
  166. Command="{x:Staticcontrols:Pagination.PrevCommand}">
  167. <PathWidh="7"Height="10"Stretch="Fill"
  168. Fill="{BindingForeground,RelativeSource={RelativeSourceAncestorType=Button}}"
  169. Data="{StaticResourcePathPrevious}"/>
  170. </Button>
  171. <ListBoxx:Name="PART_ListBox"Grid.Column="3"
  172. SelectedIndex="0"Margin="5,0"
  173. ItemsSource="{TemplateBindingPages}"
  174. Style="{StaticResourcePageListBoxStyleKey}"
  175. ItemContainerStyle="{StaticResourcePageListBoxItemStyleKey}"
  176. ScrollViewer.HorizontalScrollBarVisibility="Hidden"
  177. ScrollViewer.VerticalScrollBarVisibility="Hidden">
  178. <ListBox.ItemsPanel>
  179. <ItemsPanelTemplate>
  180. <UniformGridRows="1"/>
  181. </ItemsPanelTemplate>
  182. </ListBox.ItemsPanel>
  183. </ListBox>
  184. <ButtonGrid.Column="4"
  185. Command="{x:Staticcontrols:Pagination.NextCommand}">
  186. <PathWidth="7"Height="10"Stretch="Fill"
  187. Fill="{BindingForeground,RelativeSource={RelativeSourceAncestorType=Button}}"
  188. Data="{StaticResourcePathNext}"/>
  189. </Button>
  190. <StackPanelGrid.Column="5"Orientation="Horizontal">
  191. <TextBlockText="前往"VerticalAlignment="Center"/>
  192. <TextBoxx:Name="PART_JumpPageTextBox"
  193. TextAlignment="Center"
  194. ContextMenu="{x:Null}"
  195. Width="60"VerticalContentAlignment="Center"
  196. MinWidth="0"
  197. FontSize="{TemplateBindingFontSize}"/>
  198. <TextBlockText="页"VerticalAlignment="Center"/>
  199. </StackPanel>
  200. </Grid>
  201. </Border>
  202. </ControlTemplate>
  203. </Setter.Value>
  204. </Setter>
  205. <Style.Triggers>
  206. <TriggerProperty="IsLite"Value="true">
  207. <SetterProperty="Template"Value="{StaticResourceLitePagerControlTemplate}"/>
  208. </Trigger>
  209. </Style.Triggers>
  210. </Style>
  211. </ResourceDictionary>
复制代码
3) 创建PaginationExampleVM.cs如下:
  1. usingSystem.Collections.Generic;
  2. usingSystem.Collections.ObjectModel;
  3. usingSystem.Linq;
  4. namespaceWPFDevelopers.Samples.ViewModels
  5. {
  6. publicclassPaginationExampleVM:ViewModelBase
  7. {
  8. privateList<int>_sourceList=newList<int>();
  9. publicPaginationExampleVM()
  10. {
  11. _sourceList.AddRange(Enumerable.Range(1,300));
  12. Count=300;
  13. CurrentPageChanged();
  14. }
  15. publicObservableCollection<int>PaginationCollection{get;set;}=newObservableCollection<int>();
  16. privateint_count;
  17. publicintCount
  18. {
  19. get{return_count;}
  20. set{_count=value;this.NotifyPropertyChange("Count");CurrentPageChanged();}
  21. }
  22. privateint_countPerPage=10;
  23. publicintCountPerPage
  24. {
  25. get{return_countPerPage;}
  26. set{_countPerPage=value;this.NotifyPropertyChange("CountPerPage");CurrentPageChanged();}
  27. }
  28. privateint_current=1;
  29. publicintCurrent
  30. {
  31. get{return_current;}
  32. set{_current=value;this.NotifyPropertyChange("Current");CurrentPageChanged();}
  33. }
  34. privatevoidCurrentPageChanged()
  35. {
  36. PaginationCollection.Clear();
  37. foreach(variin_sourceList.Skip((Current-1)*CountPerPage).Take(CountPerPage))
  38. {
  39. PaginationCollection.Add(i);
  40. }
  41. }
  42. }
  43. }
复制代码
4) 使用 PaginationExample.xaml 如下:
  1. <UserControlx:Class="WPFDevelopers.Samples.ExampleViews.PaginationExample"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  5. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  6. xmlns:wpfdev="https://github.com/WPFDevelopersOrg/WPFDevelopers"
  7. xmlns:local="clr-namespace:WPFDevelopers.Samples.ExampleViews"
  8. mc:Ignorable="d"
  9. d:DesignHeight="450"d:DesignWidth="800">
  10. <UserControl.Resources>
  11. <StyleTargetType="{x:TypeTextBlock}">
  12. <SetterProperty="Foreground"Value="{DynamicResourcePrimaryTextSolidColorBrush}"/>
  13. <SetterProperty="FontSize"Value="{StaticResourceNormalFontSize}"/>
  14. <SetterProperty="VerticalAlignment"Value="Center"/>
  15. </Style>
  16. </UserControl.Resources>
  17. <Grid>
  18. <Grid.RowDefinitions>
  19. <RowDefinitionHeight="50"/>
  20. <RowDefinition/>
  21. <RowDefinitionHeight="40"/>
  22. </Grid.RowDefinitions>
  23. <Grid.ColumnDefinitions>
  24. <ColumnDefinitionWidth="2*"/>
  25. <ColumnDefinitionWidth="30"/>
  26. <ColumnDefinitionWidth="*"/>
  27. </Grid.ColumnDefinitions>
  28. <TextBlockText="正常模式分页"HorizontalAlignment="Center"VerticalAlignment="Center"/>
  29. <TextBlockGrid.Column="2"Text="精简模式分页"HorizontalAlignment="Center"VerticalAlignment="Center"/>
  30. <ListBoxGrid.Row="1"Grid.Column="0"ItemsSource="{BindingNormalPaginationViewModel.PaginationCollection}"Margin="20,0,0,0"/>
  31. <ListBoxGrid.Row="1"Grid.Column="2"ItemsSource="{BindingLitePaginationViewModel.PaginationCollection}"Margin="0,0,20,0"/>
  32. <wpfdev:PaginationGrid.Row="2"Grid.Column="0"IsLite="False"Margin="20,0,0,0"
  33. Count="{BindingNormalPaginationViewModel.Count,Mode=TwoWay}"
  34. CountPerPage="{BindingNormalPaginationViewModel.CountPerPage,Mode=TwoWay}"
  35. Current="{BindingNormalPaginationViewModel.Current,Mode=TwoWay}"/>
  36. <wpfdev:PaginationGrid.Row="2"Grid.Column="2"IsLite="true"Margin="0,0,20,0"
  37. Count="{BindingLitePaginationViewModel.Count,Mode=TwoWay}"
  38. CountPerPage="{BindingLitePaginationViewModel.CountPerPage,Mode=TwoWay}"
  39. Current="{BindingLitePaginationViewModel.Current,Mode=TwoWay}"/>
  40. </Grid>
  41. </UserControl>
复制代码
5) 使用PaginationExample.xaml.cs如下:
  1. usingSystem.Windows.Controls;
  2. usingWPFDevelopers.Samples.ViewModels;
  3. namespaceWPFDevelopers.Samples.ExampleViews
  4. {
  5. ///<summary>
  6. ///PaginationExample.xaml的交互逻辑
  7. ///</summary>
  8. publicpartialclassPaginationExample:UserControl
  9. {
  10. publicPaginationExampleVMNormalPaginationViewModel{get;set;}=newPaginationExampleVM();
  11. publicPaginationxampleVMLitePaginationViewModel{get;set;}=newPaginationExampleVM();
  12. publicPaginationExample()
  13. {
  14. InitializeComponent();
  15. this.DataContext=this;
  16. }
  17. }
  18. }
复制代码
实现效果


以上就是WPF实现列表分页控件的示例代码的详细内容,更多关于WPF列表分页控件的资料请关注中国红客联盟其它相关文章!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行