我正在开发一个用户控件,并希望使用路由事件。我注意到提供了两个委托(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/