自定義分頁控制項

来源:https://www.cnblogs.com/yinyuessh/p/18205496
-Advertisement-
Play Games

自定義分頁控制項 tip: 該控制項的樣式用的是materialDesign庫,需要下載Nuget包 Code Xaml <UserControl x:Class="TestTool.CustomControls.PagingControl" xmlns="http://schemas.microsof ...


自定義分頁控制項

tip: 該控制項的樣式用的是materialDesign庫,需要下載Nuget包

Code

  • Xaml
<UserControl
    x:Class="TestTool.CustomControls.PagingControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Name="pagingControl"
    TextElement.FontSize="14"
    mc:Ignorable="d">
    <UserControl.Resources>
        <Style TargetType="Button" BasedOn="{StaticResource MaterialDesignIconButton}">
            <Setter Property="Width" Value="26" />
            <Setter Property="Height" Value="26" />
        </Style>
    </UserControl.Resources>
    <StackPanel DataContext="{Binding ElementName=pagingControl}" Orientation="Horizontal">
        <Button
            Click="Button_FirstPage_Click"
            ToolTip="首頁">
            <materialDesign:PackIcon
                Width="24"
                Height="24"
                VerticalAlignment="Center"
                Kind="PageFirst" />
        </Button>
        <Button
            Margin="10,0,10,0"
            Click="Button_Previous_Click"
            ToolTip="上一頁">
            <materialDesign:PackIcon
                Width="20"
                Height="20"
                VerticalAlignment="Center"
                Kind="ArrowLeftCircle" />
        </Button>
        <TextBlock VerticalAlignment="Center" Text="{Binding CurrentPageIndex}" />
        <TextBlock VerticalAlignment="Center">/</TextBlock>
        <TextBlock VerticalAlignment="Center" Text="{Binding TotalPageCount}" />
        <Button
            Width="26"
            Height="26"
            Margin="10,0,0,0"
            Click="Button_Next_Click"
            ToolTip="下一頁">
            <materialDesign:PackIcon
                Width="20"
                Height="20"
                VerticalAlignment="Center"
                Kind="ArrowRightCircle" />
        </Button>
        <Button
            Margin="10,0,0,0"
            Click="Button_Last_Click"
            ToolTip="尾頁">
            <materialDesign:PackIcon
                Width="24"
                Height="24"
                VerticalAlignment="Center"
                Kind="PageLast" />
        </Button>
        <TextBlock Margin="20,0,0,0" VerticalAlignment="Center">共</TextBlock>
        <TextBlock
            Margin="5,0,0,0"
            VerticalAlignment="Center"
            Text="{Binding TotalCount}" />
        <TextBlock Margin="5,0,0,0" VerticalAlignment="Center">條記錄</TextBlock>
        <Separator
            Height="14"
            Margin="10,0,0,0"
            BorderThickness="0.5"
            Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
        <TextBlock Margin="10,0,0,0" VerticalAlignment="Center">每頁數量</TextBlock>
        <ComboBox
            MinWidth="50"
            Margin="5,0,0,0"
            VerticalContentAlignment="Center"
            ItemsSource="{Binding PagesSizes}"
            SelectedIndex="0"
            SelectedItem="{Binding CurrentPageSize}"
            SelectionChanged="ComboBox_PageSize_SelectionChanged" />
        <Separator
            Height="14"
            Margin="10,0,0,0"
            BorderThickness="0.5"
            Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
        <TextBlock Margin="10,0,0,0" VerticalAlignment="Center">跳轉到第</TextBlock>
        <TextBox
            Width="50"
            Margin="5,0,5,0"
            VerticalAlignment="Center"
            HorizontalContentAlignment="Center"
            Text="{Binding GotoPageIndex}" />
        <TextBlock VerticalAlignment="Center">頁</TextBlock>
        <Button
            Margin="5,0,0,0"
            Click="Button_Goto_Click"
            ToolTip="跳轉">
            <materialDesign:PackIcon
                Width="24"
                Height="24"
                VerticalAlignment="Center"
                Kind="ArrowRightBold" />
        </Button>
    </StackPanel>
</UserControl>
  • C#
public partial class PagingControl : UserControl, INotifyPropertyChanged
{
    // 用於防抖、節流
    private readonly ConcurrentQueue<DateTime> _operationTime = new();

    //用於防抖、節流,攔截兩次時間少於1秒的操作
    private readonly TimeSpan _ignoreOperationLessThen = TimeSpan.FromSeconds(1);

    public event EventHandler CanExecuteChanged;
    public event PropertyChangedEventHandler? PropertyChanged;

    #region 普通屬性
    /// <summary>
    /// 能否執行狀態
    /// </summary>
    public bool CanExecute => QueryCommand?.CanExecute(null) ?? true;
    //在load後是否立即觸發命令和路由事件
    public bool LoadedTrigger { get; set; } = false;
    public ObservableCollection<int> PagesSizes { get; set; } = [15, 30, 60, 200, 500, 2000];

    /// <summary>
    /// 總頁數
    /// </summary>
    private int _totalPageCount;
    public int TotalPageCount
    {
        get => _totalPageCount;
        set
        {
            if (_totalPageCount != value)
            {
                _totalPageCount = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TotalPageCount)));
            }
        }
    }

    /// <summary>
    /// 跳轉頁碼
    /// </summary>
    private int _gotoPageIndex;
    public int GotoPageIndex
    {
        get => _gotoPageIndex;
        set
        {
            if (_gotoPageIndex != value)
            {
                _gotoPageIndex = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(GotoPageIndex)));
            }
        }
    }

    /// <summary>
    /// 當前頁大小
    /// </summary>
    private int _currentPageSize = 15;
    public int CurrentPageSize
    {
        get => _currentPageSize;
        set
        {
            if (_currentPageSize != value)
            {
                _currentPageSize = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentPageSize)));
            }
        }
    }

    /// <summary>
    /// 當前頁碼
    /// </summary>
    private int _currentPageIndex;
    public int CurrentPageIndex
    {
        get => _currentPageIndex;
        set
        {
            if (_currentPageIndex != value)
            {
                _currentPageIndex = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentPageIndex)));
            }
        }
    }

    //用於外部綁定命令
    public ICommand PageQueryCommand { get; }
    #endregion

    #region 依賴屬性
    /// <summary>
    /// 總數
    /// </summary>
    public int TotalCount
    {
        get { return (int)GetValue(TotalCountProperty); }
        set { SetValue(TotalCountProperty, value); }
    }
    public ICommand QueryCommand
    {
        get { return (ICommand)GetValue(QueryCommandProperty); }
        set { SetValue(QueryCommandProperty, value); }
    }

    public static readonly DependencyProperty TotalCountProperty =
        DependencyProperty.Register("TotalCount", typeof(int), typeof(PagingControl), new FrameworkPropertyMetadata(15, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, TotalCountChangedCallback));

    public static readonly DependencyProperty QueryCommandProperty =
        DependencyProperty.Register("QueryCommand", typeof(ICommand), typeof(PagingControl), new PropertyMetadata(null, QueryCommandChangedCallback));

    #endregion

    public static readonly RoutedEvent PagingChangedEvent = EventManager.RegisterRoutedEvent("PagingChanged", RoutingStrategy.Bubble, typeof(EventHandler<PagingChangedEventArgs>), typeof(PagingControl));

    public event RoutedEventHandler PagingChanged
    {
        add => AddHandler(PagingChangedEvent, value);
        remove => RemoveHandler(PagingChangedEvent, value);
    }

    /// <summary>
    /// 構造函數
    /// </summary>
    public PagingControl()
    {
        InitializeComponent();

        TotalCount = 0;
        GotoPageIndex = 1;
        CurrentPageIndex = 0;
        TotalPageCount = 0;

        PageQueryCommand = new PageQueryCommand(this);
    }

    static void TotalCountChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        PagingControl pagingControl = (PagingControl)d;
        pagingControl.ReLoad((int)e.NewValue);
    }

    static void QueryCommandChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var command = e.NewValue as ICommand;
        if (command != null)
        {
            PagingControl pagingControl = (PagingControl)d;

            command.CanExecuteChanged -= pagingControl.Command_CanExecuteChanged;
            command.CanExecuteChanged += pagingControl.Command_CanExecuteChanged;

            if (pagingControl.LoadedTrigger)
                pagingControl.FirstPage();
        }
    }

    private void Command_CanExecuteChanged(object? sender, EventArgs e)
    {
        CanExecuteChanged?.Invoke(this, e);
        IsEnabled = QueryCommand.CanExecute(null);
    }

    #region 事件
    /// <summary>
    /// 每頁大小  ComboBox 變化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ComboBox_PageSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ReLoad(TotalCount);

        CurrentPageIndex = 1;
        OnPagingChanged(CurrentPageIndex);
        e.Handled = true;
    }

    /// <summary>
    /// 首頁按鈕點擊事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Button_FirstPage_Click(object sender, RoutedEventArgs e)
    {
        FirstPage();
        e.Handled = true;
    }

    /// <summary>
    /// 尾頁按鈕點擊事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Button_Last_Click(object sender, RoutedEventArgs e)
    {
        LastPage();
        e.Handled = true;
    }

    /// <summary>
    /// 上一頁按鈕點擊事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Button_Previous_Click(object sender, RoutedEventArgs e)
    {
        PreviousPage();
        e.Handled = true;
    }

    /// <summary>
    /// 下一頁按鈕點擊事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Button_Next_Click(object sender, RoutedEventArgs e)
    {
        NextPage();
        e.Handled = true;
    }

    /// <summary>
    /// 跳轉按鈕點擊事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Button_Goto_Click(object sender, RoutedEventArgs e)
    {
        GoToPage();
        e.Handled = true;
    }
    #endregion

    private void ReLoad(int totalCount)
    {
        TotalPageCount = (totalCount + CurrentPageSize - 1) / CurrentPageSize;

        if (TotalPageCount == 0)
            CurrentPageIndex = 0;
        else if (TotalPageCount != 0 && CurrentPageIndex == 0)
            CurrentPageIndex = 1;
    }

    private bool CheckCanExcetue()
    {
        if (_operationTime.TryDequeue(out var time))
        {
            if (DateTime.Now - time < _ignoreOperationLessThen)
                return false;
        }
        _operationTime.Enqueue(DateTime.Now);

        return CanExecute;
    }

    public void FirstPage()
    {
        if (!CheckCanExcetue()) return;

        CurrentPageIndex = 1;
        OnPagingChanged(CurrentPageIndex);
    }

    public void LastPage()
    {
        if (!CheckCanExcetue()) return;

        if (TotalPageCount == 0)
        {
            OnPagingChanged(1);
        }
        else
        {
            CurrentPageIndex = TotalPageCount;
            OnPagingChanged(CurrentPageIndex);
        }
    }

    public void NextPage()
    {
        if (!CheckCanExcetue()) return;

        if (CurrentPageIndex >= TotalPageCount)
        {
            OnPagingChanged(CurrentPageIndex);
        }
        else
        {
            CurrentPageIndex++;
            OnPagingChanged(CurrentPageIndex);
        }
    }

    public void PreviousPage()
    {
        if (!CheckCanExcetue()) return;

        if (CurrentPageIndex > TotalPageCount)
        {
            CurrentPageIndex = TotalPageCount;
        }

        if (CurrentPageIndex > 1)
        {
            CurrentPageIndex--;
            OnPagingChanged(CurrentPageIndex);
        }
        else
        {
            OnPagingChanged(1);
        }
    }

    public void GoToPage()
    {
        if (!CheckCanExcetue()) return;

        if (GotoPageIndex < 1 || GotoPageIndex > TotalPageCount)
            return;

        CurrentPageIndex = GotoPageIndex;
        OnPagingChanged(CurrentPageIndex);
    }

    private void OnPagingChanged(int pageIndex)
    {
        PagingChangedEventArgs pagingChangedEventArgs = new(PagingChangedEvent, this,
            new PagingInfo(pageIndex, CurrentPageSize));

        RaiseEvent(pagingChangedEventArgs);

        QueryCommand?.Execute(new PagingInfo(pageIndex, CurrentPageSize));
    }
}

相關自定義類

public record class PagingInfo(int TargetPageIndex, int PageSize);

路由事件參數

public class PagingChangedEventArgs(RoutedEvent routedEvent, object source, PagingInfo pageInfo) : RoutedEventArgs(routedEvent, source)
{
    public PagingInfo PageInfo { get; set; } = pageInfo;
}

外部綁定命令(用於MVVM模式下,需要其它地方觸發分頁控制項命令)

public class PageQueryCommand : ICommand
{
    private readonly PagingControl _pagingControl;

    public event EventHandler? CanExecuteChanged;

    public PageQueryCommand(PagingControl pagingControl)
    {
        _pagingControl = pagingControl;
        _pagingControl.CanExecuteChanged += (o, e) => CanExecuteChanged?.Invoke(o, e);
    }

    public bool CanExecute(object? parameter)
    {
        return _pagingControl?.CanExecute ?? true;
    }

    public void Execute(object? parameter)
    {
        _pagingControl.FirstPage();
    }
}

Demo

  • 當點擊分頁控制項按鈕時會觸發QueryCommand命令和路由事件,並傳入相關參數,需要在查詢完結果後將查詢到的總數賦值給TotalCount以便更新UI顯示的相關信息
  • 當需要外部按鈕來激發查詢命令時,可綁定分頁控制項的pageQueryCommand
<Button
    x:Name="buttonQuery"
    Margin="10,0,0,0"
    HorizontalAlignment="Stretch"
    Content="查詢"
    Command="{Binding ElementName=pageControl, Path=PageQueryCommand}"/>
<customControls:PagingControl
    x:Name="pageControl"
    HorizontalAlignment="Right"
    DockPanel.Dock="Bottom"
    LoadedTrigger="False"
    QueryCommand="{Binding PageQueryCommand}"
    TotalCount="{Binding TotalCount}" />

 [RelayCommand]
    private async Task PageQuery(PagingInfo pagingInfo){
//通過資料庫進行查詢
TotalCount=查出結果數量
    }

希望能給你帶來幫助 --來自.net菜雞粉絲的祝願


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 今天使用Thinkphp5做非同步任務傳遞where參數時遇到一個問題: 有一段如下代碼: $where['jst.supplier'] = ['exp', Db::raw('>0 or jst.is_supplier=1')]; 在使用swoole做非同步任務時需要把where參數傳遞給非同步任務處理, ...
  • 前言 市面上關於認證授權的框架已經比較豐富了,大都是關於單體應用的認證授權,在分散式架構下,使用比較多的方案是--<應用網關>,網關里集中認證,將認證通過的請求再轉發給代理的服務,這種中心化的方式並不適用於微服務,這裡討論另一種方案--<認證中心>,利用jwt去中心化的特性,減輕認證中心的壓力,有理 ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • 在小公司中,往往沒有一個前後端分離的大型團隊,去各司其職的負責構建web應用程式。面對比較簡單的需求,可能所謂團隊只有一個人,既要開發前端又要開發後端。 如果能有一項技術,能夠前後端通吃,並且具備非常高的開發效率,那就非常適合小公司的小型項目的小型甚至一人團隊來使用了。 aspdotnet就是這樣高 ...
  • 結構體 struct 是一種用戶自定義的值類型,常用於定義一些簡單(輕量)的數據結構。對於一些局部使用的數據結構,優先使用結構體,效率要高很多。 ...
  • 在很早之前,就想過開發一款抽獎軟體,卻一直沒有實際去做,最近經過一段時間的準備,終於開發出了一款基於WPF+Sqlite版的抽獎軟體,包括客戶端和管理端。本項目主要是為了熟悉WPF開發流程,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 安裝nuget包 Wesky.Net.OpenTools 1.0.8或以上版本。支持.net framework 4.6以上版本,以及所有.net core以及以上版本引用。 開發一個簡單的Winform界面,用來測試使用。如需該winform的demo,可以在公眾號【Dotnet Dancer】後 ...
  • 最近群里有個小伙伴把Dapper遷移SqlSugar幾個不能解決的問題進行一個彙總,我正好寫一篇文章來講解一下 一、sql where in傳參問題: SELECT * FROM users where id IN @ids 答: SqlSugar中應該是 var sql="SELECT * FRO ...
一周排行
    -Advertisement-
    Play Games
  • 問題 有很多應用程式在驗證JSON數據的時候用到了JSON Schema。 在微服務架構下,有時候各個微服務由於各種歷史原因,它們所生成的數據對JSON Object屬性名的大小寫規則可能並不統一,它們需要消費的JSON數據的屬性名可能需要大小寫無關。 遺憾的是,目前的JSON Schema沒有這方 ...
  • 首先下載centos07鏡像,建議使用阿裡雲推薦的地址: https://mirrors.aliyun.com/centos/7.9.2009/isos/x86_64/?spm=a2c6h.25603864.0.0.59b5f5ad5Nfr0X 其實這裡就已經出現第一個坑了 centos 07 /u ...
  • 相信很多.NETer看了標題,都會忍不住好奇,點進來看看,並且順便準備要噴作者! 這裡,首先要申明一下,作者本人也非常喜歡Linq,也在各個項目中常用Linq。 我愛Linq,Linq優雅萬歲!!!(PS:順便吐槽一下,隔壁Java從8.0版本推出的Streams API,抄了個四不像,一點都不優雅 ...
  • 在人生的重要時刻,我站在了畢業的門檻上,望著前方的道路,心中涌動著對未來的無限憧憬與些許忐忑。面前,兩條道路蜿蜒伸展:一是繼續在職場中尋求穩定,一是勇敢地走出一條屬於自己的創新之路。儘管面臨年齡和現實的挑戰,我仍舊選擇勇往直前,用技術這把鑰匙,開啟新的人生篇章。 迴首過去,我深知時間寶貴,精力有限。 ...
  • 單元測試 前言 時隔多個月,終於抽空學習了點新知識,那麼這次來記錄一下C#怎麼進行單元測試,單元測試是做什麼的。 我相信大部分剛畢業的都很疑惑單元測試是乾什麼的?在小廠實習了6個月後,我發現每天除了寫CRUD就是寫CRUD,幾乎用不到單元測試。寫完一個功能直接上手去測,當然這隻是我個人感受,僅供參考 ...
  • 一:背景 1. 講故事 最近在分析dump時,發現有程式的卡死和WeakReference有關,在以前只知道怎麼用,但不清楚底層邏輯走向是什麼樣的,藉著這個dump的契機來簡單研究下。 二:弱引用的玩法 1. 一些基礎概念 用過WeakReference的朋友都知道這裡面又可以分為弱短和弱長兩個概念 ...
  • 最近想把ET打表工具的報錯提示直接調用win系統彈窗,好讓策劃明顯的知道表格哪裡填錯數據,彈窗需要調用System.Windows.Forms庫。操作如下: 需要在 .csproj 文件中添加: <UseWindowsForms>true</UseWindowsForms> 須將目標平臺設置為 Wi ...
  • 從C#3開始,拓展方法這一特性就得到了廣泛的應用。 此功能允許你能夠使用實例方法的語法調用某個靜態方法,以下是一個獲取/創建文件的靜態方法: public static async Task<StorageFile> GetOrCreateFileAsync(this StorageFolder f ...
  • 在Windows 11下,使用WinUI2.6以上版本的ListView長這樣: 然而到了Win10上,儘管其他控制項的樣式沒有改變,但ListViewItem變成了預設樣式(初代Fluent) 最重大的問題是,Win10上的HorizontalAlignment未被設置成Stretch,可能造成嚴重 ...
  • 前言 周六在公司加班,幹完活後越顯無聊,想著下載RabbiitMQ做個小項目玩玩。然而這一下就下載了2個小時,真讓人頭痛。 簡單的講一下如何安裝吧,網上教程和踩坑文章還是很多的,我講我感覺有用的文章放在本文末尾。 安裝地址 erlang 下載 - Erlang/OTP https://www.erl ...