我嘗試了自定義路由事件,但在與附加事件處理程序一起編譯時遇到了TargetInvocationException。在WPF中使用自定義RoutedEvent導致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>
隨着後面的主窗口代碼如下處理:
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">
有人能幫忙嗎?我錯過了什麼/誤用了什麼?
非常感謝
是'的InnerException'的'TargetInvocationException'設置?通常'TargetInvocationException'包裝真正的問題。 – CodeNaked
我的歉意,@CodeNaked,你是正當的。 「InnerException」是「對象引用未設置爲對象的實例」。 –