代码之家  ›  专栏  ›  技术社区  ›  devdigital

在WPF中路由事件-使用操作委托

  •  2
  • devdigital  · 技术社区  · 15 年前

    我正在开发一个用户控件,并希望使用路由事件。我注意到提供了两个委托-RoutedEventHandler和RoutedPropertyChangedEventHandler。第一个不传递任何信息,第二个接受属性更改的新旧值。但是,我只需要传递一条信息,所以我需要相当于一个动作委托。是否提供了什么?我可以使用行动代表吗?

    1 回复  |  直到 11 年前
        1
  •  5
  •   Quartermeister    15 年前

    创建RoutedEventargs的子类以保存附加数据,并使用 EventHandler<T> 你的args类。这将转换为routedeventhandler,您的处理程序中将提供其他数据。

    您可以创建一个包含任何类型的单个参数的通用RoutedEventargs类,但是创建一个新类通常会使代码更容易读取,并且更容易修改,以便将来包含更多参数。

    public class FooEventArgs
        : RoutedEventArgs
    {
        // Declare additional data to pass here
        public string Data { get; set; }
    }
    
    public class FooControl
        : UserControl
    {
        public static readonly RoutedEvent FooEvent =
            EventManager.RegisterRoutedEvent("Foo", RoutingStrategy.Bubble, 
                typeof(EventHandler<FooEventArgs>), typeof(FooControl));
    
        public event EventHandler<FooEventArgs> Foo
        {
            add { AddHandler(FooEvent, value); }
            remove { RemoveHandler(FooEvent, value); }
        }
    
        protected void OnFoo()
        {
            base.RaiseEvent(new FooEventArgs()
            {
                RoutedEvent = FooEvent,
                // Supply the data here
                Data = "data",
            });
        }
    }