【问题标题】:Routed Events in WPF - using an Action delegateWPF 中的路由事件 - 使用操作委托
【发布时间】:2010-08-23 10:03:02
【问题描述】:

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

【问题讨论】:

    标签: wpf routed-events


    【解决方案1】:

    创建 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",
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      相关资源
      最近更新 更多