题
我正在开发一个用户控件,并希望使用路由事件。我注意到提供了两个代表 - RoutedEventHandler和RoutedPropertychangedeventhandler。第一个不会传递任何信息,而第二个则将属性的旧值和新值变化。但是,我只需要传递一条信息,因此我希望等同于动作代表。有什么东西吗?我可以使用动作委托吗?
解决方案
创建一个子类,以保存您的其他数据,并使用 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",
});
}
}
不隶属于 StackOverflow