wpf - WPF 中的路由事件 - 使用操作委托(delegate)

标签 wpf routed-events

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

最佳答案

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

关于wpf - WPF 中的路由事件 - 使用操作委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3546505/

相关文章:

c# - WPF 中的日期和数字本地化

c# - 最小化图像的内存消耗列表框(WPF)

WPF 应用程序在 vs2k8 中构建,但不在带有 msbuild 的命令行上

wpf - .NET 4.0 和 WindowsFormstHost 的窗口焦点问题

c# - 在事件触发器中处理自定义 RoutedEvent

wpf - 事件 'foo' 不是 RoutedEvent

c# wpf MVVM 从 ObservableDictionary 获取 ObservableList

c# - WPF 中的自定义附加事件

c# - 将 UserControl 中的事件绑定(bind)到父窗口路由事件 - C# XAML

wpf - 使用 Style 在许多 WPF 元素中处理 Window 的 RoutedEvent