我有一个声明为路由事件的事件(名称已更改以保护无辜者):
public class DragHelper : DependencyObject {
public static readonly RoutedEvent DragCompleteEvent = EventManager.RegisterRoutedEvent(
"DragComplete",
RoutingStrategy.Bubble,
typeof(DragRoutedEventHandler),
typeof(DragHelper)
);
public static void AddDragCompleteHandler( DependencyObject dependencyObject, DragRoutedEventHandler handler ) {
UIElement element = dependencyObject as UIElement;
if (element != null) {
element.AddHandler(DragCompleteEvent, handler);
}
}
public static void RemoveDragCompleteHandler( DependencyObject dependencyObject, DragRoutedEventHandler handler ) {
UIElement element = dependencyObject as UIElement;
if (element != null) {
element.RemoveHandler(DragCompleteEvent, handler);
}
}
非常标准的内容。在XAML中,我有一个包含单个自定义控件的DataTemplate。我试图将这个事件(以及其他一些附加属性)附加到控件上:
<DataTemplate ...>
<My:CustomControl
My:DragHelper.IsDragSource="True"
My:DragHelper.DragComplete="DragCompleteHandler" />
</DataTemplate>
这无法产生期望的结果。具体来说,虽然调用DragComplete事件的RaiseEvent()代码被调用,但处理程序从未被调用。实际上,在此XAML文件中其他任何已连接的自定义路由事件的处理程序也没有被调用。
我尝试更改路由事件的名称,并尝试将数据模板从带有DataType的模板更改为带有x:Key的模板。但是,行为在外观上没有发生变化。
但是,如果我将My:CustomControl更改为任何内置的WPF控件,例如TextBlock,则事件会按照我所期望的精确触发。同样,如果我将自定义控件替换为项目中的任何其他自定义UserControl子类,则行为会恢复到破损的状态,即似乎永远不会处理任何事件。
这对我来说毫无意义。我需要做一些特定的事情才能使此场景正常工作吗?看起来应该不重要。我想可能是我在所有自定义控件中都做了某些特定的事情导致事件处理出现问题,但到目前为止,我还没有看到任何共同点。