我如何在 style->eventsetter 中处理我的自定义事件?

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

我在我的用户控件中制作了自定义事件处理程序:

public partial class FooControl
{
   public event RoutedEventHandler AddFoo;

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

当我想这样处理事件时,一切正常:

<controls:FooControl AddFoo="FooControl_OnAddFoo"/>

我想那样做,但后来出现崩溃,我不知道为什么。

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

更多信息: 编辑器在 EventSetter 中为 AddFoo 下划线并说

编辑:

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();
}

您的活动需要是路由活动。

根据您的代码,路由事件注册不正确。

这是正确的:

// '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); }
}

请注意活动名称。不要将它与事件 ID 属性 混淆。这很重要。