昨天的代码经过大佬的指点,又优化了一下,
看看优化了哪些:
在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改变的时候,响应改变事件喽。
如果喜欢,点个赞呗~