0

我在我的用户控件中创建了一个自定义事件处理程序:

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

1 回答 1

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

于 2019-01-11T09:06:46.730 回答