我已经在用户控件中创建了一个自定义事件处理程序:
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();
}
答案 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属性混淆。这很重要。