1、事件的本质是委托处理
2、实例创建
2)、Tunnel:下沉 (隧道)从根到源, eg. Window——>Grid——>Button (Handled不处理)
2、实例创建
1)、路由事件定义+注册
public static readonly RoutedEvent CustomClickEvent = EventManager.RegisterRoutedEvent("CustomClick", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(CustomizedButton));
2)、属性包装(add+remove)
public event RoutedEventHandler CustomClick
{
add { AddHandler(CustomClickEvent, value); }
remove { RemoveHandler(CustomClickEvent, value); }
}
3)、事件触发
void RaiseCustomClick()
{
RoutedEventArgs routedEventArgs = new RoutedEventArgs(CustomizedButton.CustomClickEvent);
RaiseEvent(routedEventArgs);
}
4)、重写事件的方法
protected override void OnClick()
{
RaiseCustomClick();
}
5)、界面
<Window x:Class="CustimizedRouteEvent.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:custom="clr-namespace:CustimizedRouteEvent"
mc:Ignorable="d" Loaded="Window_Loaded"
custom:CustomizedButton.CustomClick ="Window_CustomClick"
Title="MainWindow" Height="450" Width="800">
<Grid Name="MyGrid" custom:CustomizedButton.CustomClick ="Grid_CustomClick">
<custom:CustomizedButton CustomClick="CustomizedButton_CustomClick" x:Name="customButton" Background="Green" >
<Button Name="InnerButton" Background="Beige" Width="300" Height="200" Click="InnerButton_Click"/>
</custom:CustomizedButton >
</Grid>
</Window>
6)、类事件处理函数
public class CustomizedButton : Button
{
static CustomizedButton()
{
//即使已经处理也再处理,最后一个参数TRUE,为已有路由事件添加新的委托处理
EventManager.RegisterClassHandler(typeof(CustomizedButton), CustomClickEvent, new RoutedEventHandler(CustomClickClassHandler), true);
}
/// <summary>
/// 一般CLR事件处理
/// </summary>
public event EventHandler ClassEventHandler;
public static void CustomClickClassHandler(object sender, RoutedEventArgs e)
{
CustomizedButton customizedButton = sender as CustomizedButton;
EventArgs eventArgs = new EventArgs();
customizedButton.ClassEventHandler(CustomizedButton.ClickEvent, eventArgs);
}
}
public MainWindow()
{
InitializeComponent();
this.customButton.ClassEventHandler += new EventHandler(ClassEventHandler);
}
private void ClassEventHandler(object sender, EventArgs e)
{
Console.WriteLine("ClassEventHandler" + "//" + e.ToString() + "//" + sender.ToString());
}
3、路由政策
1)、Bubble:上浮 (冒泡)从源到根,eg. Button——>Grid——>Window (Handled不处理)2)、Tunnel:下沉 (隧道)从根到源, eg. Window——>Grid——>Button (Handled不处理)
3)、Direct :Button