简体   繁体   中英

how can i handle my custom event in style->eventsetter?

I have made a custom event handler in my usercontrol:

public partial class FooControl
{
   public event RoutedEventHandler AddFoo;

   private void AddFoo_Click(object sender, RoutedEventArgs e)
   {
       if (AddFoo != null)
           AddFoo(this, new RoutedEventArgs());
   }
}

when I want to handle the event like this, everything works fine:

<controls:FooControl AddFoo="FooControl_OnAddFoo"/>

I wanted to do it like that but then something crashes and I don't know why.

<Style TargetType="controls:FooControl">
    <EventSetter Event="AddFoo" Handler="Event_AddFoo"/>
</Style>

Further information: the editor underlines AddFoo in the EventSetter and says

  • the event "AddFoo" is not a routed event
  • routed event descriptor field "AddFooEvent" missing
  • throws an exception: Exception thrown: 'System.Windows.Markup.XamlParseException' in PresentationFramework.dll
  • inner exception says value must not be null

EDIT:

public static readonly RoutedEvent AddEvent = 
                               EventManager.RegisterRoutedEvent
                               ("AddEvent", RoutingStrategy.Bubble, 
                               typeof(RoutedEventHandler), typeof(FooControl));
public event RoutedEventHandler AddFoo
{
    add { AddHandler(AddEvent, value); }
    remove { RemoveHandler(AddEvent, value); }
}

void RaiseAddEvent()
{
    RoutedEventArgs newEventArgs = new RoutedEventArgs(FooControl.AddEvent);
    RaiseEvent(newEventArgs);
}

private void AddFoo_Click(object sender, RoutedEventArgs e)
{
    RaiseAddEvent();
}

Your event needs to be a routed event.

According to your code, the routed event registration is incorrect.

Here is the right one:

// 'AddEvent' is the name of the property that holds the routed event ID 
public static readonly RoutedEvent AddEvent = EventManager.RegisterRoutedEvent
    ("Add", // the event name is 'Add'
    RoutingStrategy.Bubble, 
    typeof(RoutedEventHandler),
    typeof(FooControl));

// The event name is 'Add'
public event RoutedEventHandler Add
{
    add { AddHandler(AddEvent, value); }
    remove { RemoveHandler(AddEvent, value); }
}

Please pay attention to the event name. Don't confuse it with the event ID property. This is important.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM