我正在尝试自定义路由事件,但在使用附加事件处理程序进行编译时出现 TargetInvocationException。
我在自定义控件中有以下代码EventRaiserControl
:
public static readonly RoutedEvent KickedEvent = EventManager.RegisterRoutedEvent("KickedEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(EventRaiserControl));
public event RoutedEventHandler Kicked
{
add
{ this.AddHandler(KickedEvent, value); }
remove
{ this.RemoveHandler(KickedEvent, value); }
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
RaiseEvent(new RoutedEventArgs(KickedEvent));
}
然后,我的主窗口中有以下 XAML:
<StackPanel local:EventRaiserControl.Kicked="StackPanel_Kicked">
<local:EventRaiserControl Kicked="EventRaiserControl_Kicked"/>
</StackPanel>
在 MainWindow 代码中使用以下处理程序:
private void StackPanel_Kicked(object sender, RoutedEventArgs e)
{
Console.WriteLine("Caught Kicked Event at Panel level.");
}
private void EventRaiserControl_Kicked(object sender, RoutedEventArgs e)
{
Console.WriteLine("Caught Kicked Event at Control level.");
}
我的代码适用于这个处理程序:
<local:EventRaiserControl Kicked="EventRaiserControl_Kicked"/>
TargetInvocationException
但是在我添加附加的处理程序的那一刻失败了:
<StackPanel local:EventRaiserControl.Kicked="StackPanel_Kicked">
有人可以帮忙吗?我错过了什么/滥用什么?
非常感谢