C# codes:
using System.Windows;
namespace WpfApplication6
{
public class Dog : UIElement //继承UIElement及其子类,因为AddHandler,RemoveHandler,RaiseHandler在UIElemnt中实现
{
public static readonly RoutedEvent RunRoutedEvent =
EventManager.RegisterRoutedEvent("Run", RoutingStrategy.Bubble, typeof(RunRoutedEventHandler), typeof(Dog));
public event RunRoutedEventHandler Run //自定义事件,通过自定义时间为路由事件RunRoutedEvent加载、卸载方法
{
add { this.AddHandler(RunRoutedEvent, value); }
remove { this.RemoveHandler(RunRoutedEvent, value); }
}
public void Invoker(RunRoutedEventArgs e) //自定义Invoke方法
{
this.RaiseEvent(e);
}
}
public class RunRoutedEventArgs : RoutedEventArgs //自定义EventArgs,实现一个构造函数,参数包含RoutedEvent
{
public RunRoutedEventArgs(RoutedEvent routedEvent, object source)
: base(routedEvent, source)
{ }
public string Name { get; set; }
}
public delegate void RunRoutedEventHandler(object sender, RunRoutedEventArgs e); //自定义EventHandler
}
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:proj="clr-namespace:WpfApplication6"
Title="MainWindow" Height="350" Width="525">
<Grid>
<proj:Dog x:Name="dog" Run="dog_Run" />
<Button Content="Button" HorizontalAlignment="Left" Margin="143,101,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void dog_Run(object sender, RunRoutedEventArgs e)
{
MessageBox.Show("Sender: "+ sender.ToString() +
Environment.NewLine + "OriginalSource: "+ e.OriginalSource +
Environment.NewLine + "Source: " + e.Source +
Environment.NewLine + "Dog Name: " + e.Name);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.dog.Invoker(new RunRoutedEventArgs(Dog.RunRoutedEvent, this) { Name = "Wangwang" });
}
}
个人感觉自定义路由事件类似于依赖属性,附加属性:
UIElement对应于DependencyObject,
Run事件包装器钟的AddHandler,RemoveHandler对应于依赖属性,附加属性的GetValue,SetValue方法
不同的是自定义路由事件需要一个RaiseEvent方法来Invoke事件中加载的方法。
AddHandler,RemoveHandler,RaiseHandler是RoutedEvent的三个最基础的方法,均定义在UIElement类中。