WPF中的路由事件 - 使用Action委托

dev*_*tal 2 wpf routed-events

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

Qua*_*ter 5

创建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",
        });
    }
}
Run Code Online (Sandbox Code Playgroud)