首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >WPF实现列表分页控件的示例代码分享

WPF实现列表分页控件的示例代码分享

原创
作者头像
用户7718188
发布于 2022-11-06 12:22:29
发布于 2022-11-06 12:22:29
1.6K0
举报
文章被收录于专栏:高级工程司高级工程司

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

<ColumnDefinition Width="Auto"/><ColumnDefinition Width="10"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="10"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="5"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="5"/><ColumnDefinition Width="Auto"/>

1) Pagination.cs 如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Input;

using WPFDevelopers.Helpers;

namespace WPFDevelopers.Controls

{

    [TemplatePart(Name = CountPerPageTextBoxTemplateName, Type = typeof(TextBox))]

    [TemplatePart(Name = JustPageTextBoxTemplateName, Type = typeof(TextBox))]

    [TemplatePart(Name = ListBoxTemplateName, Type = typeof(ListBox))]

    public class Pagination : Control

    {

        private const string CountPerPageTextBoxTemplateName = "PART_CountPerPageTextBox";

        private const string JustPageTextBoxTemplateName = "PART_JumpPageTextBox";

        private const string ListBoxTemplateName = "PART_ListBox";

        private const string Ellipsis = "···";

        private static readonly Type _typeofSelf = typeof(Pagination);

        private TextBox _countPerPageTextBox;

        private TextBox _jumpPageTextBox;

        private ListBox _listBox;

        static Pagination()

        {

            InitializeCommands();

            DefaultStyleKeyProperty.OverrideMetadata(_typeofSelf, new FrameworkPropertyMetadata(_typeofSelf));

        }

        #region Override

        public override void OnApplyTemplate()

        {

            base.OnApplyTemplate();

            UnsubscribeEvents();

            _countPerPageTextBox = GetTemplateChild(CountPerPageTextBoxTemplateName) as TextBox;

            if (_countPerPageTextBox != null)

            {

                _countPerPageTextBox.ContextMenu = null;

                _countPerPageTextBox.PreviewTextInput += _countPerPageTextBox_PreviewTextInput;

                _countPerPageTextBox.PreviewKeyDown += _countPerPageTextBox_PreviewKeyDown;

            }

            _jumpPageTextBox = GetTemplateChild(JustPageTextBoxTemplateName) as TextBox;

            if (_jumpPageTextBox != null)

            {

                _jumpPageTextBox.ContextMenu = null;

                _jumpPageTextBox.PreviewTextInput += _countPerPageTextBox_PreviewTextInput;

                _jumpPageTextBox.PreviewKeyDown += _countPerPageTextBox_PreviewKeyDown;

            }

            _listBox = GetTemplateChild(ListBoxTemplateName) as ListBox;

            Init();

            SubscribeEvents();

        }

        private void _countPerPageTextBox_PreviewKeyDown(object sender, KeyEventArgs e)

        {

            if (Key.Space == e.Key

                ||

                Key.V == e.Key

                && e.KeyboardDevice.Modifiers == ModifierKeys.Control)

                e.Handled = true;

        }

        private void _countPerPageTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)

        {

            e.Handled = ControlsHelper.IsNumber(e.Text);

        }

        #endregion

        #region Command

        private static void InitializeCommands()

        {

            PrevCommand = new RoutedCommand("Prev", _typeofSelf);

            NextCommand = new RoutedCommand("Next", _typeofSelf);

            CommandManager.RegisterClassCommandBinding(_typeofSelf,

                new CommandBinding(PrevCommand, OnPrevCommand, OnCanPrevCommand));

            CommandManager.RegisterClassCommandBinding(_typeofSelf,

                new CommandBinding(NextCommand, OnNextCommand, OnCanNextCommand));

        }

        public static RoutedCommand PrevCommand { get; private set; }

        public static RoutedCommand NextCommand { get; private set; }

        private static void OnPrevCommand(object sender, RoutedEventArgs e)

        {

            var ctrl = sender as Pagination;

            ctrl.Current--;

        }

        private static void OnCanPrevCommand(object sender, CanExecuteRoutedEventArgs e)

        {

            var ctrl = sender as Pagination;

            e.CanExecute = ctrl.Current > 1;

        }

        private static void OnNextCommand(object sender, RoutedEventArgs e)

        {

            var ctrl = sender as Pagination;

            ctrl.Current++;

        }

        private static void OnCanNextCommand(object sender, CanExecuteRoutedEventArgs e)

        {

            var ctrl = sender as Pagination;

            e.CanExecute = ctrl.Current < ctrl.PageCount;

        }

        #endregion

        #region Properties

        private static readonly DependencyPropertyKey PagesPropertyKey =

            DependencyProperty.RegisterReadOnly("Pages", typeof(IEnumerable<string>), _typeofSelf,

                new PropertyMetadata(null));

        public static readonly DependencyProperty PagesProperty = PagesPropertyKey.DependencyProperty;

        public IEnumerable<string> Pages => (IEnumerable<string>) GetValue(PagesProperty);

        private static readonly DependencyPropertyKey PageCountPropertyKey =

            DependencyProperty.RegisterReadOnly("PageCount", typeof(int), _typeofSelf,

                new PropertyMetadata(1, OnPageCountPropertyChanged));

        public static readonly DependencyProperty PageCountProperty = PageCountPropertyKey.DependencyProperty;

        public int PageCount => (int) GetValue(PageCountProperty);

        private static void OnPageCountPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            var ctrl = d as Pagination;

            var pageCount = (int) e.NewValue;

            /*

            if (ctrl._jumpPageTextBox != null)

                ctrl._jumpPageTextBox.Maximum = pageCount;

            */

        }

        public static readonly DependencyProperty IsLiteProperty =

            DependencyProperty.Register("IsLite", typeof(bool), _typeofSelf, new PropertyMetadata(false));

        public bool IsLite

        {

            get => (bool) GetValue(IsLiteProperty);

            set => SetValue(IsLiteProperty, value);

        }

        public static readonly DependencyProperty CountProperty = DependencyProperty.Register("Count", typeof(int),

            _typeofSelf, new PropertyMetadata(0, OnCountPropertyChanged, CoerceCount));

        public int Count

        {

            get => (int) GetValue(CountProperty);

            set => SetValue(CountProperty, value);

        }

        private static object CoerceCount(DependencyObject d, object value)

        {

            var count = (int) value;

            return Math.Max(count, 0);

        }

        private static void OnCountPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            var ctrl = d as Pagination;

            var count = (int) e.NewValue;

            ctrl.SetValue(PageCountPropertyKey, (int) Math.Ceiling(count * 1.0 / ctrl.CountPerPage));

            ctrl.UpdatePages();

        }

        public static readonly DependencyProperty CountPerPageProperty = DependencyProperty.Register("CountPerPage",

            typeof(int), _typeofSelf, new PropertyMetadata(50, OnCountPerPagePropertyChanged, CoerceCountPerPage));

        public int CountPerPage

        {

            get => (int) GetValue(CountPerPageProperty);

            set => SetValue(CountPerPageProperty, value);

        }

        private static object CoerceCountPerPage(DependencyObject d, object value)

        {

            var countPerPage = (int) value;

            return Math.Max(countPerPage, 1);

        }

        private static void OnCountPerPagePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            var ctrl = d as Pagination;

            var countPerPage = (int) e.NewValue;

            if (ctrl._countPerPageTextBox != null)

                ctrl._countPerPageTextBox.Text = countPerPage.ToString();

            ctrl.SetValue(PageCountPropertyKey, (int) Math.Ceiling(ctrl.Count * 1.0 / countPerPage));

            if (ctrl.Current != 1)

                ctrl.Current = 1;

            else

                ctrl.UpdatePages();

        }

        public static readonly DependencyProperty CurrentProperty = DependencyProperty.Register("Current", typeof(int),

            _typeofSelf, new PropertyMetadata(1, OnCurrentPropertyChanged, CoerceCurrent));

        public int Current

        {

            get => (int) GetValue(CurrentProperty);

            set => SetValue(CurrentProperty, value);

        }

        private static object CoerceCurrent(DependencyObject d, object value)

        {

            var current = (int) value;

            var ctrl = d as Pagination;

            return Math.Max(current, 1);

        }

        private static void OnCurrentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            var ctrl = d as Pagination;

            var current = (int) e.NewValue;

            if (ctrl._listBox != null)

                ctrl._listBox.SelectedItem = current.ToString();

            if (ctrl._jumpPageTextBox != null)

                ctrl._jumpPageTextBox.Text = current.ToString();

            ctrl.UpdatePages();

        }

        #endregion

        #region Event

        /// <summary>

        ///     分页

        /// </summary>

        private void OnCountPerPageTextBoxChanged(object sender, TextChangedEventArgs e)

        {

            if (int.TryParse(_countPerPageTextBox.Text, out var _ountPerPage))

                CountPerPage = _ountPerPage;

        }

        /// <summary>

        ///     跳转页

        /// </summary>

        private void OnJumpPageTextBoxChanged(object sender, TextChangedEventArgs e)

        {

            if (int.TryParse(_jumpPageTextBox.Text, out var _current))

                Current = _current;

        }

        /// <summary>

        ///     选择页

        /// </summary>

        private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)

        {

            if (_listBox.SelectedItem == null)

                return;

            Current = int.Parse(_listBox.SelectedItem.ToString());

        }

        #endregion

        #region Private

        private void Init()

        {

            SetValue(PageCountPropertyKey, (int) Math.Ceiling(Count * 1.0 / CountPerPage));

            _jumpPageTextBox.Text = Current.ToString();

            //_jumpPageTextBox.Maximum = PageCount;

            _countPerPageTextBox.Text = CountPerPage.ToString();

            if (_listBox != null)

                _listBox.SelectedItem = Current.ToString();

        }

        private void UnsubscribeEvents()

        {

            if (_countPerPageTextBox != null)

                _countPerPageTextBox.TextChanged -= OnCountPerPageTextBoxChanged;

            if (_jumpPageTextBox != null)

                _jumpPageTextBox.TextChanged -= OnJumpPageTextBoxChanged;

            if (_listBox != null)

                _listBox.SelectionChanged -= OnSelectionChanged;

        }

        private void SubscribeEvents()

        {

            if (_countPerPageTextBox != null)

                _countPerPageTextBox.TextChanged += OnCountPerPageTextBoxChanged;

            if (_jumpPageTextBox != null)

                _jumpPageTextBox.TextChanged += OnJumpPageTextBoxChanged;

            if (_listBox != null)

                _listBox.SelectionChanged += OnSelectionChanged;

        }

        private void UpdatePages()

        {

            SetValue(PagesPropertyKey, GetPagers(Count, Current));

            if (_listBox != null && _listBox.SelectedItem == null)

                _listBox.SelectedItem = Current.ToString();

        }

        private IEnumerable<string> GetPagers(int count, int current)

        {

            if (count == 0)

                return null;

            if (PageCount <= 7)

                return Enumerable.Range(1, PageCount).Select(p => p.ToString()).ToArray();

            if (current <= 4)

                return new[] {"1", "2", "3", "4", "5", Ellipsis, PageCount.ToString()};

            if (current >= PageCount - 3)

                return new[]

                {

                    "1", Ellipsis, (PageCount - 4).ToString(), (PageCount - 3).ToString(), (PageCount - 2).ToString(),

                    (PageCount - 1).ToString(), PageCount.ToString()

                };

            return new[]

            {

                "1", Ellipsis, (current - 1).ToString(), current.ToString(), (current + 1).ToString(), Ellipsis,

                PageCount.ToString()

            };

        }

        #endregion

    }

}

2) Pagination.xaml 如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

                    xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"

                    xmlns:helpers="clr-namespace:WPFDevelopers.Helpers"

                    xmlns:controls="clr-namespace:WPFDevelopers.Controls">

    <ResourceDictionary.MergedDictionaries>

        <ResourceDictionary Source="Basic/ControlBasic.xaml"/>

    </ResourceDictionary.MergedDictionaries>

    <Style x:Key="PageListBoxStyleKey" TargetType="{x:Type ListBox}" 

           BasedOn="{StaticResource ControlBasicStyle}">

        <Setter Property="Background" Value="Transparent"/>

        <Setter Property="BorderThickness" Value="0"/>

        <Setter Property="Padding" Value="0"/>

        <Setter Property="Template">

            <Setter.Value>

                <ControlTemplate TargetType="{x:Type ListBox}">

                    <Border BorderBrush="{TemplateBinding BorderBrush}" 

                            BorderThickness="{TemplateBinding BorderThickness}" 

                            Background="{TemplateBinding Background}" 

                            SnapsToDevicePixels="True">

                        <ScrollViewer Focusable="False" Padding="{TemplateBinding Padding}">

                            <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>

                        </ScrollViewer>

                    </Border>

                    <ControlTemplate.Triggers>

                        <Trigger Property="IsGrouping" Value="True">

                            <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>

                        </Trigger>

                    </ControlTemplate.Triggers>

                </ControlTemplate>

            </Setter.Value>

        </Setter>

    </Style>

    <Style x:Key="PageListBoxItemStyleKey" 

           TargetType="{x:Type ListBoxItem}"

           BasedOn="{StaticResource ControlBasicStyle}">

        <Setter Property="MinWidth" Value="32"/>

        <Setter Property="Cursor" Value="Hand"/>

        <Setter Property="HorizontalContentAlignment" Value="Center"/>

        <Setter Property="VerticalContentAlignment" Value="Center"/>

        <Setter Property="helpers:ElementHelper.CornerRadius" Value="3"/>

        <Setter Property="BorderThickness" Value="1"/>

        <Setter Property="Padding" Value="5,0"/>

        <Setter Property="Margin" Value="3,0"/>

        <Setter Property="Background" Value="{DynamicResource BackgroundSolidColorBrush}"/>

        <Setter Property="BorderBrush" Value="{DynamicResource BaseSolidColorBrush}"/>

        <Setter Property="Template">

            <Setter.Value>

                <ControlTemplate TargetType="{x:Type ListBoxItem}">

                    <Border SnapsToDevicePixels="True"

                            Background="{TemplateBinding Background}" 

                            BorderThickness="{TemplateBinding BorderThickness}" 

                            BorderBrush="{TemplateBinding BorderBrush}"  

                            Padding="{TemplateBinding Padding}"

                            CornerRadius="{Binding Path=(helpers:ElementHelper.CornerRadius),RelativeSource={RelativeSource TemplatedParent}}">

                        <ContentPresenter x:Name="PART_ContentPresenter" 

                                         HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 

                                         VerticalAlignment="{TemplateBinding VerticalContentAlignment}"

                                         RecognizesAccessKey="True" 

                                         TextElement.Foreground="{TemplateBinding Foreground}"/>

                    </Border>

                </ControlTemplate>

            </Setter.Value>

        </Setter>

        <Style.Triggers>

            <DataTrigger Binding="{Binding .}" Value="···">

                <Setter Property="IsEnabled" Value="False"/>

                <Setter Property="FontWeight" Value="Bold"/>

            </DataTrigger>

            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="BorderBrush" Value="{DynamicResource DefaultBorderBrushSolidColorBrush}"/>

                <Setter Property="Background" Value="{DynamicResource DefaultBackgroundSolidColorBrush}"/>

                <Setter Property="Foreground" Value="{DynamicResource PrimaryNormalSolidColorBrush}"/>

            </Trigger>

            <Trigger Property="IsSelected" Value="True">

                <Setter Property="Background" Value="{DynamicResource PrimaryPressedSolidColorBrush}"/>

                <Setter Property="TextElement.Foreground" Value="{DynamicResource WindowForegroundColorBrush}"/>

            </Trigger>

        </Style.Triggers>

    </Style>

    <ControlTemplate x:Key="LitePagerControlTemplate" TargetType="{x:Type controls:Pagination}">

        <Border Background="{TemplateBinding Background}"

                BorderBrush="{TemplateBinding BorderBrush}"

                BorderThickness="{TemplateBinding BorderThickness}"

                Padding="{TemplateBinding Padding}">

            <Grid>

                <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="Auto"/>

                    <ColumnDefinition Width="10"/>

                    <ColumnDefinition Width="Auto"/>

                    <ColumnDefinition Width="Auto"/>

                    <ColumnDefinition Width="10"/>

                    <ColumnDefinition Width="Auto"/>

                    <ColumnDefinition Width="5"/>

                    <ColumnDefinition Width="Auto"/>

                    <ColumnDefinition Width="5"/>

                    <ColumnDefinition Width="Auto"/>

                </Grid.ColumnDefinitions>

                <TextBlock VerticalAlignment="Center"

                           Text="{Binding Count,StringFormat=共 {0} 条,RelativeSource={RelativeSource TemplatedParent}}"/>

               

                <TextBox Grid.Column="2" x:Name="PART_CountPerPageTextBox" 

                         TextAlignment="Center" VerticalContentAlignment="Center"

                         Width="60" MinWidth="0"

                         input:InputMethod.IsInputMethodEnabled="False"/>

                <TextBlock Grid.Column="3" Text=" 条 / 页" VerticalAlignment="Center"/>

                <Button Grid.Column="5" 

                        Command="{x:Static controls:Pagination.PrevCommand}">

                    <Path Width="7" Height="10" Stretch="Fill" 

                          Fill="{Binding Foreground,RelativeSource={RelativeSource AncestorType=Button}}"

                          Data="{StaticResource PathPrevious}"/>

                </Button>

                

                <TextBox Grid.Column="7" x:Name="PART_JumpPageTextBox" 

                         TextAlignment="Center" 

                         VerticalContentAlignment="Center"

                         Width="60" MinWidth="0">

                    <TextBox.ToolTip>

                        <TextBlock>

                            <TextBlock.Text>

                                <MultiBinding StringFormat="{}{0}/{1}">

                                    <Binding Path="Current" RelativeSource="{RelativeSource TemplatedParent}"/>

                                    <Binding Path="PageCount" RelativeSource="{RelativeSource TemplatedParent}"/>

                                </MultiBinding>

                            </TextBlock.Text>

                        </TextBlock>

                    </TextBox.ToolTip>

                </TextBox>

                <Button Grid.Column="9" 

                        Command="{x:Static controls:Pagination.NextCommand}">

                    <Path Width="7" Height="10" Stretch="Fill" 

                          Fill="{Binding Foreground,RelativeSource={RelativeSource AncestorType=Button}}"

                          Data="{StaticResource PathNext}"/>

                </Button>

            </Grid>

        </Border>

    </ControlTemplate>

    <Style TargetType="{x:Type controls:Pagination}" 

           BasedOn="{StaticResource ControlBasicStyle}">

        <Setter Property="Template">

            <Setter.Value>

                <ControlTemplate TargetType="{x:Type controls:Pagination}">

                    <Border Background="{TemplateBinding Background}"

                            BorderBrush="{TemplateBinding BorderBrush}"

                            BorderThickness="{TemplateBinding BorderThickness}"

                            Padding="{TemplateBinding Padding}">

                        <Grid>

                            <Grid.ColumnDefinitions>

                                <ColumnDefinition Width="Auto"/>

                                <ColumnDefinition Width="Auto"/>

                                <ColumnDefinition Width="Auto"/>

                                <ColumnDefinition Width="*"/>

                                <ColumnDefinition Width="Auto"/>

                                <ColumnDefinition Width="Auto"/>

                            </Grid.ColumnDefinitions>

                            <TextBlock Margin="0,0,15,0" VerticalAlignment="Center"

                                       Text="{Binding Count,StringFormat=共 {0} 条,RelativeSource={RelativeSource TemplatedParent}}"/>

                            <StackPanel Grid.Column="1" Orientation="Horizontal" Margin="0,0,15,0" >

                                <TextBlock Text="每页 " VerticalAlignment="Center"/>

                                <TextBox x:Name="PART_CountPerPageTextBox" 

                                         TextAlignment="Center" Width="60"

                                         MinWidth="0" VerticalContentAlignment="Center"

                                         FontSize="{TemplateBinding FontSize}" 

                                         input:InputMethod.IsInputMethodEnabled="False"/>

                                <TextBlock Text=" 条" VerticalAlignment="Center"/>

                            </StackPanel>

                            <Button Grid.Column="2" 

                                    Command="{x:Static controls:Pagination.PrevCommand}">

                                <Path Width="7" Height="10" Stretch="Fill" 

                                      Fill="{Binding Foreground,RelativeSource={RelativeSource AncestorType=Button}}"

                                      Data="{StaticResource PathPrevious}"/>

                            </Button>

                            <ListBox x:Name="PART_ListBox" Grid.Column="3"

                                     SelectedIndex="0" Margin="5,0"

                                     ItemsSource="{TemplateBinding Pages}"

                                     Style="{StaticResource PageListBoxStyleKey}"

                                     ItemContainerStyle="{StaticResource PageListBoxItemStyleKey}"

                                     ScrollViewer.HorizontalScrollBarVisibility="Hidden"

                                     ScrollViewer.VerticalScrollBarVisibility="Hidden">

                                <ListBox.ItemsPanel>

                                    <ItemsPanelTemplate>

                                        <UniformGrid Rows="1"/>

                                    </ItemsPanelTemplate>

                                </ListBox.ItemsPanel>

                            </ListBox>

                            <Button Grid.Column="4" 

                                    Command="{x:Static controls:Pagination.NextCommand}">

                                <Path Width="7" Height="10" Stretch="Fill" 

                                      Fill="{Binding Foreground,RelativeSource={RelativeSource AncestorType=Button}}"

                                      Data="{StaticResource PathNext}"/>

                            </Button>

                            <StackPanel Grid.Column="5" Orientation="Horizontal">

                                <TextBlock Text=" 前往 " VerticalAlignment="Center"/>

                               

                                <TextBox x:Name="PART_JumpPageTextBox"

                                         TextAlignment="Center" 

                                         ContextMenu="{x:Null}"

                                         Width="60" VerticalContentAlignment="Center"

                                         MinWidth="0"

                                         FontSize="{TemplateBinding FontSize}" />

                                <TextBlock Text=" 页" VerticalAlignment="Center"/>

                            </StackPanel>

                        </Grid>

                    </Border>

                </ControlTemplate>

            </Setter.Value>

        </Setter>

        <Style.Triggers>

            <Trigger Property="IsLite" Value="true">

                <Setter Property="Template" Value="{StaticResource LitePagerControlTemplate}"/>

            </Trigger>

        </Style.Triggers>

    </Style>

</ResourceDictionary>

3) 创建PaginationExampleVM.cs如下:

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.Linq;

namespace WPFDevelopers.Samples.ViewModels

{

    public class PaginationExampleVM : ViewModelBase

    {

        private List<int> _sourceList = new List<int>();

        public PaginationExampleVM()

        {

            _sourceList.AddRange(Enumerable.Range(1, 300));

            Count = 300;

            CurrentPageChanged();

        }

        public ObservableCollection<int> PaginationCollection { get; set; } = new ObservableCollection<int>();

        private int _count;

        public int Count

        {

            get { return _count; }

            set { _count = value;  this.NotifyPropertyChange("Count"); CurrentPageChanged(); }

        }

        private int _countPerPage = 10;

        public int CountPerPage

        {

            get { return _countPerPage; }

            set { _countPerPage = value; this.NotifyPropertyChange("CountPerPage"); CurrentPageChanged(); }

        }

        private int _current = 1;

        public int Current

        {

            get { return _current; }

            set { _current = value; this.NotifyPropertyChange("Current"); CurrentPageChanged(); }

        }

        private void CurrentPageChanged()

        {

            PaginationCollection.Clear();

            foreach (var i in _sourceList.Skip((Current - 1) * CountPerPage).Take(CountPerPage))

            {

                PaginationCollection.Add(i);

            }

        }

    }

}

4) 使用 PaginationExample.xaml 如下:

<UserControl x:Class="WPFDevelopers.Samples.ExampleViews.PaginationExample"

             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" 

             xmlns:wpfdev="https://github.com/WPFDevelopersOrg/WPFDevelopers"

             xmlns:local="clr-namespace:WPFDevelopers.Samples.ExampleViews"

             mc:Ignorable="d" 

             d:DesignHeight="450" d:DesignWidth="800">

    <UserControl.Resources>

        <Style TargetType="{x:Type TextBlock}">

            <Setter Property="Foreground" Value="{DynamicResource PrimaryTextSolidColorBrush}" />

            <Setter Property="FontSize" Value="{StaticResource NormalFontSize}"/>

            <Setter Property="VerticalAlignment" Value="Center"/>

        </Style>

    </UserControl.Resources>

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="50"/>

            <RowDefinition/>

            <RowDefinition Height="40"/>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="2*"/>

            <ColumnDefinition Width="30"/>

            <ColumnDefinition Width="*"/>

        </Grid.ColumnDefinitions>

        <TextBlock Text="正常模式分页" HorizontalAlignment="Center" VerticalAlignment="Center"/>

        <TextBlock Grid.Column="2" Text="精简模式分页" HorizontalAlignment="Center" VerticalAlignment="Center"/>

        <ListBox Grid.Row="1" Grid.Column="0" ItemsSource="{Binding NormalPaginationViewModel.PaginationCollection}" Margin="20,0,0,0"/>

        <ListBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding LitePaginationViewModel.PaginationCollection}" Margin="0,0,20,0"/>

        <wpfdev:Pagination Grid.Row="2" Grid.Column="0" IsLite="False"  Margin="20,0,0,0"

                             Count="{Binding NormalPaginationViewModel.Count,Mode=TwoWay}"

                             CountPerPage="{Binding NormalPaginationViewModel.CountPerPage,Mode=TwoWay}"

                             Current="{Binding NormalPaginationViewModel.Current,Mode=TwoWay}"/>

        <wpfdev:Pagination Grid.Row="2" Grid.Column="2" IsLite="true"  Margin="0,0,20,0"

                             Count="{Binding LitePaginationViewModel.Count,Mode=TwoWay}"

                             CountPerPage="{Binding LitePaginationViewModel.CountPerPage,Mode=TwoWay}"

                             Current="{Binding LitePaginationViewModel.Current,Mode=TwoWay}"/>

    </Grid>

</UserControl>

5) 使用PaginationExample.xaml.cs如下:

using System.Windows.Controls;

using WPFDevelopers.Samples.ViewModels;

namespace WPFDevelopers.Samples.ExampleViews

{

    /// <summary>

    /// PaginationExample.xaml 的交互逻辑

    /// </summary>

    public partial class PaginationExample : UserControl

    {

        public PaginationExampleVM NormalPaginationViewModel { get; set; } = new PaginationExampleVM();

        public PaginationExampleVM LitePaginationViewModel { get; set; } = new PaginationExampleVM();

        public PaginationExample()

        {

            InitializeComponent();

            this.DataContext = this;

        }

    }

}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
WPF TreeGrid MVVM 模式下自定义表格带展开缩放效果,并且可以获取点击行的数据
MVVM其实就是:Model 、View、ViewModel三个的简称,就像MVC一样。 Model就是模型。View就是视图。ViewModel就是和view进行绑定的。
Shunnet
2022/05/31
6.5K0
WPF TreeGrid MVVM 模式下自定义表格带展开缩放效果,并且可以获取点击行的数据
如何实现日期范围选择器
原文链接: https://github.com/WPFDevelopersOrg/WPFDevelopers
郑子铭
2024/12/20
7940
如何实现日期范围选择器
【愚公系列】2023年04月 WPF运动控制平台-005.运动平台之功能实现(完结)
---- 一、运动平台之功能实现 1.位置计算 物理可用距离 (40000), 取料位:19945P, 打包位:-19360P 像素位置:取料位:20px 打包位:1020px 把脉冲转换位距离 步进驱动器设置细分 8 步进电机步进角 1.8° 导程:8mm 计算步进电机走1cm需要的脉冲数 360 / 1.8 = 200个脉冲转一圈 200 * 8 = 1600个脉冲转一圈(细分情况) 1600 / 8 = 200 (步进电机走1mm需要) 故:走1cm需要脉冲
愚公搬代码
2023/04/28
5150
【愚公系列】2023年04月 WPF运动控制平台-005.运动平台之功能实现(完结)
WPF MVVM 模式下自写自用的窗口样式
废话我也就不多说,直接上菜(由于公司电脑做了加密,无法把代码压缩发布,只能以这种方式来分享)
Shunnet
2022/09/01
1.8K0
WPF MVVM 模式下自写自用的窗口样式
WPF ListView CellTemplate Border---设置ListView单元格的边框
1. 先看图片 2. 这是styleresource;应该还能精简掉很多; dd <Window.Resources> <Color x:Key="WindowColor">#FFE8EDF9</Color> <Color x:Key="ContentAreaColorLight">#FFC5CBF9</Color> <Color x:Key="ContentAreaColorDark">#FF7381F9</Color> <Co
liulun
2022/05/09
1.9K0
WPF  ListView  CellTemplate  Border---设置ListView单元格的边框
[WPF自定义控件库]简单的表单布局控件
在WPF中布局表单一直都很传统,例如使用上面的XAML,它通过Grid布局一个表单。这样出来的结果整整齐齐,看上去没什么问题,但当系统里有几十个表单页以后需要统一将标签改为上对齐,或者标签和控件中加一个:号等需求都会难倒开发人员。一个好的做法是使用某些控件库提供的表单控件;如果不想引入一个这么“重”的东西,可以自己定义一个简单的表单控件。
dino.c
2019/06/03
2.8K0
Drawer 抽屉控件的实现
定义了一个名为 Drawer 的自定义控件,继承自 HeaderedContentControl,允许用户在应用程序中创建可展开和收起的抽屉。抽屉的显示和隐藏动画通过 Storyboard 实现,支持从不同方向(左、上、右、下)展开和收起。
郑子铭
2024/12/09
2130
Drawer 抽屉控件的实现
【愚公系列】2022年10月 基于WPF的智能制造MES系统框架-菜单栏的设计
MES系统为企业提供包括制造数据管理、计划排程管理、生产调度管理、库存管理、质量管理、人力资源管理、工作中心/设备管理、工具工装管理、采购管理、成本管理、项目看板管理、生产过程控制、底层数据集成分析、上层数据集成分解等管理模块,为企业打造一个扎实、可靠、全面、可行的制造协同管理平台。
愚公搬代码
2022/10/28
8230
WPF开源项目:WPF-ControlBase
仓库README很素,但看作者README贴的几篇博文介绍,你会喜欢上它的,废话不多说,上介绍目录:
沙漠尽头的狼
2021/12/01
3.8K0
WPF开源项目:WPF-ControlBase
SilverLight企业应用框架设计【二】框架画面
注意,这里每个顶部菜单的ICO图标不是动态的,朋友们,想让他变成动态的就自己动手吧
liulun
2022/05/09
7090
SilverLight企业应用框架设计【二】框架画面
WPF实现消息中心
本文将讲解基于WPF实现一个消息中心的功能,比如常见的软件当中会经常收到服务端推送的“新闻”、“公告”等消息。这个时候就需要对这个需求进行分析了。
JusterZhu
2022/12/07
7020
WPF实现消息中心
[UWP]新控件ColorPicker
Fall Creators Update中提供了一个新得ColorPicker控件,解决了以前选择颜色只能用Combo Box的窘境。
dino.c
2019/01/18
7790
[UWP]新控件ColorPicker
【NEW】WPF MVVM 模式下自写自用的窗口样式
SVG是一种图形文件格式,它的英文全称为Scalable Vector Graphics,意思为可缩放的矢量图形。它是基于XML(Extensible Markup Language),由World Wide Web Consortium(W3C)联盟进行开发的。严格来说应该是一种开放标准的矢量图形语言,可让你设计激动人心的、高分辨率的Web图形页面。用户可以直接用代码来描绘图像,可以用任何文字处理工具打开SVG图像,通过改变部分代码来使图像具有交互功能,并可以随时插入到HTML中通过浏览器来观看。
Shunnet
2022/09/01
2.6K0
【NEW】WPF MVVM 模式下自写自用的窗口样式
WPF-实现TextBox和PasswordBox显示背景文字
TextBox的代码实现很简单,就是通过画刷用TextBlock作背景,将TextBox背景设置为画刷构成的背景。 遇到的问题!!! 在TextBox 的代码中不能直接给Background赋值,如下面的代码。在这里赋值后,通过Style将不能修改背景,因为如下的赋值方法的优秀级较高,Style中将无法修改。建议将正常输入时的背景色设置在Style中,这样就可以避免因为优先级无法呈现效果。上面给出的代码已经将背景这只在Style中
MaybeHC
2024/04/23
2700
WPF-实现TextBox和PasswordBox显示背景文字
【愚公系列】2023年04月 WPF运动控制平台-003.运动控制平台的UI设计
---- 一、运动控制平台的UI设计 1.代码 <Window x:Class="MotionPlatform.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expr
愚公搬代码
2023/04/16
5460
【愚公系列】2023年04月 WPF运动控制平台-003.运动控制平台的UI设计
如何优雅的为文本框添加清除按钮
答:一般情况都会选择自定义控件,这样的话不清真,所以我们通过附加属性,可以让你的文本框变得更简洁。
独立观察员
2024/11/23
8230
如何优雅的为文本框添加清除按钮
WPF --- 重写圆角DataGrid样式
因要符合UI设计, 需要一个圆角的 DataGrid 样式,且需要一个更美观的滚动条,所以重写了一下微软 「WPF」 原生的 DataGrid 的样式,包含如下内容:
Niuery Diary
2023/10/22
8970
WPF --- 重写圆角DataGrid样式
记一次自定义基因分类图实现(二)
最近,心情略差,各种烦心事。总是提不起力气写点啥,但是上周写了一,这周还是把二写了吧,内容没那么多,但是总是自己的一些分享,记录。总得有个宣泄口~,发现不打游戏了,之后 的确没有什么好的爱好能够吸引我的注意力,这几年满脑子都是搞钱两个字,入迷了!
tangmanger
2025/04/26
1080
记一次自定义基因分类图实现(二)
WPF --TextBox--圆角、水印、带单位
<SolidColorBrush x:Key="TextBox.Static.Border" Color="#FFABAdB3"/> <SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="#FF7EB4EA"/> <SolidColorBrush x:Key="TextBox.Focus.Border" Color="#FF569DE5"/> <VisualBrush x:Key="HintText" TileMode=
hbbliyong
2019/09/25
1.3K0
WPF --TextBox--圆角、水印、带单位
浅谈WPF之控件拖拽与拖动
使用过office的visio软件画图的小伙伴都知道,画图软件分为两部分,左侧图形库,存放各种图标,右侧是一个画布,将左侧图形库的图标控件拖拽到右侧画布,就会生成一个新的控件,并且可以自由拖动。那如何在WPF程序中,实现类似的功能呢?今天就以一个简单的小例子,简述如何在WPF中实现控件的拖拽和拖动,仅供学习分享使用,如有不足之处,还请指正。
沙漠尽头的狼
2023/12/13
8700
浅谈WPF之控件拖拽与拖动
相关推荐
WPF TreeGrid MVVM 模式下自定义表格带展开缩放效果,并且可以获取点击行的数据
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档