自定義分頁控制項

来源: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
  • 1、預覽地址:http://139.155.137.144:9012 2、qq群:801913255 一、前言 隨著網路的發展,企業對於信息系統數據的保密工作愈發重視,不同身份、角色對於數據的訪問許可權都應該大相徑庭。 列如 1、不同登錄人員對一個數據列表的可見度是不一樣的,如數據列、數據行、數據按鈕 ...
  • 前言 上一篇文章寫瞭如何使用RabbitMQ做個簡單的發送郵件項目,然後評論也是比較多,也是準備去學習一下如何確保RabbitMQ的消息可靠性,但是由於時間原因,先來說說設計模式中的簡單工廠模式吧! 在瞭解簡單工廠模式之前,我們要知道C#是一款面向對象的高級程式語言。它有3大特性,封裝、繼承、多態。 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 介紹 Nodify是一個WPF基於節點的編輯器控制項,其中包含一系列節點、連接和連接器組件,旨在簡化構建基於節點的工具的過程 ...
  • 創建一個webapi項目做測試使用。 創建新控制器,搭建一個基礎框架,包括獲取當天日期、wiki的請求地址等 創建一個Http請求幫助類以及方法,用於獲取指定URL的信息 使用http請求訪問指定url,先運行一下,看看返回的內容。內容如圖右邊所示,實際上是一個Json數據。我們主要解析 大事記 部 ...
  • 最近在不少自媒體上看到有關.NET與C#的資訊與評價,感覺大家對.NET與C#還是不太瞭解,尤其是對2016年6月發佈的跨平臺.NET Core 1.0,更是知之甚少。在考慮一番之後,還是決定寫點東西總結一下,也回顧一下.NET的發展歷史。 首先,你沒看錯,.NET是跨平臺的,可以在Windows、 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 添加節點(nodes) 通過上一篇我們已經創建好了編輯器實例現在我們為編輯器添加一個節點 添加model和viewmode ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...
  • 類型檢查和轉換:當你需要檢查對象是否為特定類型,並且希望在同一時間內將其轉換為那個類型時,模式匹配提供了一種更簡潔的方式來完成這一任務,避免了使用傳統的as和is操作符後還需要進行額外的null檢查。 複雜條件邏輯:在處理複雜的條件邏輯時,特別是涉及到多個條件和類型的情況下,使用模式匹配可以使代碼更 ...
  • 在日常開發中,我們經常需要和文件打交道,特別是桌面開發,有時候就會需要載入大批量的文件,而且可能還會存在部分文件缺失的情況,那麼如何才能快速的判斷文件是否存在呢?如果處理不當的,且文件數量比較多的時候,可能會造成卡頓等情況,進而影響程式的使用體驗。今天就以一個簡單的小例子,簡述兩種不同的判斷文件是否... ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...