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

时间:2019-01-11 08:36:32

标签: c# wpf events user-controls 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并说

  • 事件“ AddFoo”不是路由事件
  • 路由事件描述符字段“ AddFooEvent”丢失
  • 引发异常:PresentationFramework.dll中引发异常:'System.Windows.Markup.XamlParseException'
  • 内部异常表明值不能为空

编辑:

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

1 个答案:

答案 0 :(得分:0)

您的事件必须是路由事件。

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

这里是正确的:

// '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属性混淆。这很重要。