Search code examples
wpfrouted-events

Using custom RoutedEvent in WPF causes TargetInvocationException


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


Solution

  • At first I was surprised why it is, but I saw the reason after coding as your code. Just change

    EventManager.RegisterRoutedEvent("KickedEvent"....
    

    to

    EventManager.RegisterRoutedEvent("Kicked"....