wpf 自定义路由事件

创建自定义路由事件大体可以分为三个步骤:

(1)声明并注册路由事件

(2)为路由事件添加CLR事件包装

(3)创建可以激发路由事件的方法。一般借用已有的路由事件,如click或其他

外部定于事件,

Grid1.AddHandler(Button.ClickEvent, new RoutedEventHandler(ButtonInGrid_Click)); 一般事件

Grid1.AddHandler(Button.ClickEvent, new RoutedEventHandler(ButtonInGrid_Click),true); 标注停止继续执行事件

EventManager.RegisterClassHandle 优先级最高响应的事件




事件的包括:事件,事件发布者,事件订阅者

事件的传递是沿着可视化树传递,比逻辑树更精细。

附加事件也是路由事件。

其实“附加事件”也是路由事件,只是个文字游戏,为什么还要另外起个名字呢?原来路由事件的宿主都是那些拥有可视化实体的界面元素;而附加事件则不具备显示在用户界面上的能力。

常见的附加事件有:

Binding类:SourceUpdated事件、TargetUpdated事件。

Mouse类:MouseEnter事件、MouseLeave事件、MouseDown事件、MouseUp事件等。

Keyboard类:KeyDown事件、KeyUp事件等。

using System;
using System.Windows.Controls;
using System.Windows;

namespace MyRoutedEvent
{
class TimeButton:Button
{
//声明和注册路由事件
public static readonly RoutedEvent ReportTimeRoutedEvent =
EventManager.RegisterRoutedEvent("ReportTime", RoutingStrategy.Bubble, typeof(EventHandler<ReportTimeRoutedEventArgs>), typeof(TimeButton));
//CLR事件包装
public event RoutedEventHandler ReportTime
{
add { this.AddHandler(ReportTimeRoutedEvent, value); }
remove { this.RemoveHandler(ReportTimeRoutedEvent, value); }
}
//激发路由事件,借用Click事件的激发方法

protected override void OnClick()
{
base.OnClick();//保证Button原有功能正常使用,Click事件被激发

ReportTimeRoutedEventArgs args = new ReportTimeRoutedEventArgs(ReportTimeRoutedEvent, this);
args.ClickTime = DateTime.Now;
this.RaiseEvent(args);//UIElement及其派生类
}

}
}

//定义事件参数类

using System;
using System.Windows;

namespace MyRoutedEvent
{
//事件参数
class ReportTimeRoutedEventArgs:RoutedEventArgs
{
public ReportTimeRoutedEventArgs(RoutedEvent routedEvent, object source) : base(routedEvent, source) { }

public DateTime ClickTime { get; set; }
}
}

<Window x:Class="MyRoutedEvent.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyRoutedEvent"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="grid1" local:TimeButton.ReportTime="TimeButton_ReportTime"><!---->
<Grid x:Name="grid2">
<Grid x:Name="grid3">
<StackPanel x:Name="stackPanel1">
<ListBox x:Name="listBox1"/>
<local:TimeButton Width="200" Height="200" Background="Aquamarine" ReportTime="TimeButton_ReportTime" /><!---->
</StackPanel>
</Grid>
</Grid>
</Grid>
</Window>

//后台处理方法

using System.Windows;

namespace MyRoutedEvent
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void TimeButton_ReportTime(object sender, ReportTimeRoutedEventArgs e)//注意参数
{
listBox1.Items.Add(e.ClickTime.ToLongTimeString()+"DebugLZQ");
}
}
}

原文地址:https://www.cnblogs.com/wwwfj/p/3645521.html