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
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.