我在我的用户控件中创建了一个自定义事件处理程序:
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();
}