WPF附加事件定义
路由事件的宿主都是些拥有可视化实体的界面元素。而附加事件则不具备显示在用户界面上的能力。加入和移出附件事件的两个方法命名约定:
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);
}
}

浙公网安备 33010602011771号