路由事件的宿主都是些擁有可視化實體的界面元素,而附加事件則不具備顯示在用戶界面上的能力。添加和移出附件事件的兩個方法命名約定:
1、爲目標UI元素添加附加事件偵聽器的包裝器是一個名爲Add*Handler的public static方法。星號代表事件名稱,與註冊事件時的名稱一致。2、解除UI元素對附加事件偵聽的包裝器是名爲Remove*Handler的public static方法,星號也是事件名稱。
代碼如下:
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public static readonly RoutedEvent NameChangedEvent = EventManager.RegisterRoutedEvent("NameChanged",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(Student));
public static void AddNameChangedHandler(DependencyObject d, RoutedEventHandler h)
{
UIElement element = d as UIElement;
if (element != null) element.AddHandler(Student.NameChangedEvent, h);
}
public static void RemoveNameChangedHandler(DependencyObject d, RoutedEventHandler h)
{
UIElement element = d as UIElement;
if (element != null) element.RemoveHandler(Student.NameChangedEvent, h);
}
}