前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >WPF实现列表分页控件的示例代码分享

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

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

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 删除。

评论
登录后参与评论
3 条评论
热度
最新
本科科班,标准要求
本科科班,标准要求
回复回复点赞举报
写的比较初级,还没到架构师的段位
写的比较初级,还没到架构师的段位
11点赞举报
对头,既然架构,不只是技术,而且还有非技术的东西,列举这些技术,就像建大楼你掌握了砌砖一样,但建一栋大楼还差的远的很。
对头,既然架构,不只是技术,而且还有非技术的东西,列举这些技术,就像建大楼你掌握了砌砖一样,但建一栋大楼还差的远的很。
回复回复点赞举报
推荐阅读
对比感知校准(CAC)多模态方法,为视觉语言模型开放词汇任务校准难题破局 !
视觉-语言模型,如CLIP,在庞大的网络规模文本-图像数据集上进行预训练,已在各种下游图像分类任务中展现出令人印象深刻的零样本能力和图像-文本对齐能力。针对少量 Token 数据提升视觉语言模型(VLM)在特定任务上的性能,已经提出了多种 Prompt 学习方法。
AIGC 先锋科技
2025/03/03
1270
对比感知校准(CAC)多模态方法,为视觉语言模型开放词汇任务校准难题破局 !
自监督方法提升语言模型否定鲁棒性:引入NSPP及NSP变体,在九基准测试及CondaQA表现优异 !
在人工智能(AI)的迅猛发展背景下,本研究旨在探讨人工智能领域的最新进展及其在各个行业的应用。通过对相关文献的回顾和分析,本文将概述当前AI技术的发展趋势,并展望其在未来可能带来的变革。
AIGC 先锋科技
2025/04/14
800
自监督方法提升语言模型否定鲁棒性:引入NSPP及NSP变体,在九基准测试及CondaQA表现优异 !
ICLR2020 | StructBERT : 融合语言结构的BERT模型
今天给大家介绍阿里巴巴达摩院在ICLR2020的一篇论文,该研究针对预训练语言模型BERT在预训练任务中忽略了语言结构的问题,作者对BERT进行扩展,通过加入语言结构到预训练任务中,其核心思想是在预训练任务中加入两项基于语言结构的任务:word-level ordering和sentence-level ordering。
DrugAI
2021/02/01
1.2K0
ICLR2020 | StructBERT : 融合语言结构的BERT模型
【机器学习】--- 自然语言推理(NLI)
随着自然语言处理(NLP)的迅速发展,**自然语言推理(Natural Language Inference, NLI)**已成为一项重要的研究任务。它的目标是判断两个文本片段之间的逻辑关系。这一任务广泛应用于机器阅读理解、问答系统、对话生成等场景。
Undoom
2024/09/23
4580
解密大型语言模型:从相关性中发现因果关系?
因果推理是人类智力的标志之一。因果关系NLP领域近年来引起了人们的极大兴趣,但其主要依赖于从常识知识中发现因果关系。本研究提出了一个基准数据集(CORR2CAUSE)来测试大语言模型(LLM)的纯因果推理能力。其中CORR2CAUSE对LLM来说是一项具有挑战性的任务,有助于指导未来关于提高LLM纯粹推理能力和可推广性的研究。
zenRRan
2023/08/22
6840
解密大型语言模型:从相关性中发现因果关系?
8篇论文梳理BERT相关模型进展与反思
BERT自从在arXiv上发表以来获得了很大的成功和关注,打开了NLP中2-Stage的潘多拉魔盒。随后涌现了一大批类似于“BERT”的预训练(pre-trained)模型,有引入BERT中双向上下文信息的广义自回归模型XLNet,也有改进BERT训练方式和目标的RoBERTa和SpanBERT,还有结合多任务以及知识蒸馏(Knowledge Distillation)强化BERT 的MT-DNN等。除此之外,还有人试图探究BERT的原理以及其在某些任务中表现出众的真正原因。
大数据文摘
2019/09/09
6100
8篇论文梳理BERT相关模型进展与反思
不要相信模型输出的概率打分......
大家在训练深度学习模型的时候,有没有遇到这样的场景:分类任务的准确率比较高,但是模型输出的预测概率和实际预测准确率存在比较大的差异?这就是现代深度学习模型面临的校准问题。在很多场景中,我们不仅关注分类效果或者排序效果(auc),还希望模型预测的概率也是准的。例如在自动驾驶场景中,如果模型无法以置信度较高的水平检测行人或障碍物,就应该通过输出概率反映出来,并让模型依赖其他信息进行决策。再比如在广告场景中,ctr预测除了给广告排序外,还会用于确定最终的扣费价格,如果ctr的概率预测的不准,会导致广告主的扣费偏高或偏低。
圆圆的算法笔记
2022/12/19
1.3K0
不要相信模型输出的概率打分......
深度学习应用篇-自然语言处理[10]:N-Gram、SimCSE介绍,更多技术:数据增强、智能标注、多分类算法、文本信息抽取、多模态信息抽取、模型压缩算法等
N-Gram是一种基于统计语言模型的算法。它的基本思想是将文本里面的内容按照字节进行大小为N的滑动窗口操作,形成了长度是N的字节片段序列。每一个字节片段称为gram,对所有gram的出现频度进行统计,并且按照事先设定好的阈值进行过滤,形成关键gram列表,也就是这个文本的向量特征空间,列表中的每一种gram就是一个特征向量维度。
汀丶人工智能
2023/06/12
2.9K0
深度学习应用篇-自然语言处理[10]:N-Gram、SimCSE介绍,更多技术:数据增强、智能标注、多分类算法、文本信息抽取、多模态信息抽取、模型压缩算法等
Calibration: 一个工业价值极大,学术界却鲜有研究的问题!
在实际的工业应用中,当模型的准确性无法达到预期的标准时,通常思考采用提高模型决策的阈值。而这种方法在神经网络上不一定适用。本文介绍了一篇来自2017年的ICML顶会论文,关于让模型的softmax输出能真实的反映决策的置信度,也就是Calibration问题。
AI算法与图像处理
2021/01/20
1.5K0
Calibration: 一个工业价值极大,学术界却鲜有研究的问题!
NLP简报(Issue#9)
RONEC[1]是罗马尼亚语的命名实体语料库,在约5000个带注释的句子中包含超过26000个实体,属于16个不同的类。这些句子摘自无版权的报纸,内容涉及多种样式。该语料库是罗马尼亚语言领域针对命名实体识别的第一个举措。它具有BIO和CoNLL-U Plus格式,可以在此处免费使用和扩展[2]。
NewBeeNLP
2020/08/26
1K0
NLP简报(Issue#9)
常用模型蒸馏方法:这 N 个核心,你都知道吗?(上)
Hello folks,我是 Luga,今天我们来聊一下人工智能应用场景 - 构建高效、灵活、健壮的模型技术体系。
Luga Lee
2025/05/13
680
常用模型蒸馏方法:这 N 个核心,你都知道吗?(上)
通过准确性、可解释性、校准度和忠实度,对ChatGPT的能力进行全面评估
本文主要评估了ChatGPT这种大型语言模型在信息提取方面的能力,作者使用了7个细粒度的信息提取任务来评估ChatGPT的性能、可解释性、校准度和可信度。
zenRRan
2023/08/21
5180
通过准确性、可解释性、校准度和忠实度,对ChatGPT的能力进行全面评估
自然语言处理中的迁移学习(上)
本文转载自公众号「哈工大SCIR」(微信ID:HIt_SCIR),该公众号为哈尔滨工业大学社会计算与信息检索研究中心(刘挺教授为中心主任)的师生的信息分享平台,本文作者为哈工大SCIR 徐啸。
AI科技评论
2019/10/23
1.4K0
自然语言处理中的迁移学习(上)
480万标记样本:Facebook提出「预微调」,持续提高语言模型性能
机器学习研究人员在自我监督的语言模型预训练方面取得了非凡的成功。自监督学习是不需要标记数据而进行训练。预训练是指通过一项任务来训练模型,并可应用于其他任务。
新智元
2021/03/10
2420
480万标记样本:Facebook提出「预微调」,持续提高语言模型性能
10个大型语言模型(LLM)常见面试问题和答案解析
提示校准包括调整提示,尽量减少产生的输出中的偏差。微调修改模型本身,而数据增强扩展训练数据。梯度裁剪防止在训练期间爆炸梯度。
deephub
2024/04/15
6360
10个大型语言模型(LLM)常见面试问题和答案解析
大语言模型的幕后:如何构建一个全球级AI语言系统
在过去的几年里,大型语言模型(LLMs)如OpenAI的GPT系列、Google的BERT及其衍生版本等,已经成为人工智能领域的前沿技术。这些模型不仅在自然语言处理(NLP)任务中取得了显著成果,而且正在重塑从聊天机器人到自动化创作的多个领域。尽管这些技术的应用已经非常广泛,但很多人对于它们是如何构建的,尤其是如何打造一个全球级AI语言系统,仍然存在很多疑问。
一键难忘
2025/03/25
1520
字段级概率校准,助力推荐算法更精准!
丨导语 一年一度的国际顶级学术会议万维网大会 (The Web Conference, 即 WWW-2020) 于 4 月 20 日至 4 月 24 日在线上成功召开。WWW-2020 收到来自全球五十多个国家和地区的超过 1500 篇论文投稿,仅录用长文 219 篇,录用率 19%。其中,由腾讯TEG数据平台部,与中科院计算所、清华大学合作研究的成果《Field-aware Calibration: A simple and empirically strong method for reliable
腾讯大数据
2020/05/13
2.2K0
大语言模型评测方法全面总结!
自2017年Transformer模型提出以来,自然语言处理研究逐步转向基于该框架的预训练模型,如BERT、GPT、BART和T5等。这些预训练模型与下游任务适配后,持续刷新最优结果。然而,现有评测方法存在广度和深度不足、数据偏差、忽视模型其他能力或属性评估等问题。因此,需要全面评测和深入研究模型的各项能力、属性、应用局限性、潜在风险及其可控性等。
算法进阶
2024/07/31
4560
大语言模型评测方法全面总结!
理解GPT-3: OpenAI最新的语言模型
如果你一直在关注NLP领域的最新发展,那么在过去几个月里几乎不可能避免GPT-3的炒作。这一切都始于OpenAl研究人员发表的论文《Language Models are few Shot Learners》,该论文介绍了GPT-3系列模型。
deephub
2020/09/04
2.3K0
理解GPT-3: OpenAI最新的语言模型
小版BERT也能出奇迹:最火的预训练语言库探索小巧之路
近日,HuggingFace 发布了 NLP transformer 模型——DistilBERT,该模型与 BERT 的架构类似,不过它仅使用了 6600 万参数(区别于 BERT_base 的 1.1 亿参数),却在 GLUE 基准上实现了后者 95% 的性能。
机器之心
2019/09/10
1.1K0
小版BERT也能出奇迹:最火的预训练语言库探索小巧之路
推荐阅读
相关推荐
对比感知校准(CAC)多模态方法,为视觉语言模型开放词汇任务校准难题破局 !
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档