生活随笔
收集整理的這篇文章主要介紹了
WPF 分页控件添加路由事件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
昨天的代碼經過大佬的指點,又優化了一下,
看看優化了哪些:
在Pagination類中添加事件定義:
public static readonly RoutedEvent IndexChangedEvent = EventManager.RegisterRoutedEvent("IndexChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Pagination));//CLR事件包裝public event RoutedEventHandler IndexChanged{add { this.AddHandler(IndexChangedEvent, value); }remove { this.RemoveHandler(IndexChangedEvent, value); }}
在CurrentPage的改變事件中觸發事件:
public int CurrentPage{get { return (int)GetValue(CurrentPageProperty); }set { SetValue(CurrentPageProperty, value); }}public static readonly DependencyProperty CurrentPageProperty =DependencyProperty.Register("CurrentPage", typeof(int), typeof(Pagination), new PropertyMetadata(1, (d, e) =>{if (!(d is Pagination pagination)) return;if (pagination.PageCount > 5){pagination.UpdateControl();}else{pagination.UpdateControlSimple();}RoutedEventArgs args = new RoutedEventArgs(){RoutedEvent = IndexChangedEvent,Source = pagination,};pagination.RaiseEvent(args);}));
然后,MainWindow中綁定事件:
<Window x:Class="WPFDemos.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/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WPFDemos"mc:Ignorable="d"x:Name="widnow"WindowStartupLocation="CenterScreen"UseLayoutRounding="True"Background="#F5F5F5"FontSize="16"Title="分頁" Height="500" Width="1000"><Grid><StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"><local:Pagination x:Name="pag0" PageCount="3" Height="35" HorizontalAlignment="Center"/><TextBlock Margin="10" HorizontalAlignment="Center"><Run Text="當前頁:"/><Run Text="{Binding CurrentPage,ElementName=pag0}"/></TextBlock><local:Pagination x:Name="pag" PageCount="5" Height="35" HorizontalAlignment="Center"/><TextBlock Margin="10" HorizontalAlignment="Center"><Run Text="當前頁:"/><Run Text="{Binding CurrentPage,ElementName=pag}"/></TextBlock><local:Pagination x:Name="pag1" PageCount="35" Height="35" IndexChanged="pag1_IndexChanged"/><TextBlock Margin="10" HorizontalAlignment="Center"><Run Text="當前頁:"/><Run Text="{Binding CurrentPage,ElementName=pag1}"/></TextBlock></StackPanel></Grid>
</Window>
這樣就能直接在index改變的時候,響應改變事件嘍。
如果喜歡,點個贊唄~
總結
以上是生活随笔為你收集整理的WPF 分页控件添加路由事件的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。