在 WPF 中使用自定义 RoutedEvent 会导致 TargetInitationException
我正在尝试自定义路由事件,但在使用附加事件处理程序进行编译时出现 TargetInitationException。
我在自定义控件 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"/>
但失败 <当我添加附加处理程序时,code>TargetInitationException:
<StackPanel local:EventRaiserControl.Kicked="StackPanel_Kicked">
有人可以帮忙吗?我错过/误用了什么?
非常感谢
I am trying out custom routed events, but I get a TargetInvocationException when compiling with an Attached Event Handler.
I have the following code inside custom control 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));
}
I then have the following XAML in my main window:
<StackPanel local:EventRaiserControl.Kicked="StackPanel_Kicked">
<local:EventRaiserControl Kicked="EventRaiserControl_Kicked"/>
</StackPanel>
With the following handlers in the MainWindow code behind:
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.");
}
My code works fine with this handler:
<local:EventRaiserControl Kicked="EventRaiserControl_Kicked"/>
But fails with TargetInvocationException
the moment I add the attached handler:
<StackPanel local:EventRaiserControl.Kicked="StackPanel_Kicked">
Can somebody help? What am I missing / misusing?
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
起初我很惊讶为什么会这样,但在编码为你的代码后我看到了原因。只需更改
为
At first I was surprised why it is, but I saw the reason after coding as your code. Just change
to