WPF-14:事件-2

来自《深入浅出WPF》(刘铁猛)读书笔记

RoutedEventArgs有两个属性:Source,OriginalSource,这两个属性都表示路由事件传递的起点(即事件消息的源头),只不过Source表示LogicalTree上的消息源头,而OrigianlTree则表示VisualTree上的源头。

为目标UI元素添加事件侦听器的包装器是Add*Handler的public static方法;解除UI元素对附加事件侦听的包装器是Remove*handler的public static方法。

实例:设计一个名为Student的类,如果Student实例的Name属性值发生了变化就激发一个路由事件。

1)Student类中声明并定义路由事件

public static readonly RoutedEvent  NameChangedEvent = EventManager.RegisterRoutedEvent ("NameChanged", RoutingStrategy.Bubble,typeof(RoutedEventHandler),typeof(Student));

2)在Student类中为界面元素添加路由事件侦听

public static void AddNameChangedHandler(DependencyObject d, RoutedEventHandler h)
{
    UIElement e=d as UIElement;
    if(e!=null)
    {
        e.AddHandler(Student.NameChangedEvent,h);
    }
}

3)Student类中移除侦听

public static RemoveNameChangedHandler(DependencyObject d, RoutedEventHandler h)
{
    UIElement e= d as UiElement;
    if(e!=null)
    {
        e.RemoveHandler(Student.NameChangedEvent,h);
    }
}

4)补充Student的两个属性

public int Id {get;set;}
public string Name {get;set;}

5)实际应用

public Window1()
{
    InitializeComponent();
    //为外层Grid添加事件侦听器
    Student.AddNameChangedHandler(this.gridMain, new RoutedEventHandler(this.StudentNameChangedHandler));
}

UIElement类是路由事件宿主与附加路由事件宿主的分水岭,不单是因为从UIElement类开始才具备了在界面上显示的能力,还因为RaiseEvent,AddHandler,RemoveHandler这些方法也定义在UIElement中。



猜你喜欢

转载自blog.csdn.net/huan_126/article/details/80107521
今日推荐