且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在运行时将 EventSetter 动态添加到现有分层数据模板

更新时间:2023-11-12 18:53:52

我自己解决了这个问题,我想在这里发布代码以供将来参考.也许这不是***的解决方案,但它对我有用.我在 DragDropDecorator 类的 Loaded 事件中添加了以下几行:

I fixed the problem by myself and I would like to post the code here for future reference. Maybe this is not the best solution, but it works for me. I added the following lines to the Loaded event of the DragDropDecorator class:

if (itemsControl.GetType() == typeof(TreeView))
{
    var originalStyle = itemsControl.Style;
    var newStyle = new Style();
    newStyle.BasedOn = originalStyle;

    newStyle.Setters.Add(new EventSetter(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(ItemsControl_PreviewMouseLeftButtonDown)));
    newStyle.Setters.Add(new EventSetter(PreviewMouseMoveEvent, new MouseEventHandler(ItemsControl_PreviewMouseMove)));
    newStyle.Setters.Add(new EventSetter(PreviewMouseLeftButtonUpEvent, new MouseButtonEventHandler(ItemsControl_PreviewMouseLeftButtonUp)));
    newStyle.Setters.Add(new EventSetter(PreviewDropEvent, new DragEventHandler(ItemsControl_PreviewDrop)));
    newStyle.Setters.Add(new EventSetter(PreviewQueryContinueDragEvent, new QueryContinueDragEventHandler(ItemsControl_PreviewQueryContinueDrag)));
    newStyle.Setters.Add(new EventSetter(PreviewDragEnterEvent, new DragEventHandler(ItemsControl_PreviewDragEnter)));
    newStyle.Setters.Add(new EventSetter(PreviewDragOverEvent, new DragEventHandler(ItemsControl_PreviewDragOver)));
    newStyle.Setters.Add(new EventSetter(DragLeaveEvent, new DragEventHandler(ItemsControl_DragLeave)));

    itemsControl.ItemContainerStyle = newStyle;
}

我无法编辑样式,因为一旦设置它就会被密封.因此,我在新样式对象上使用了 BasedOn 属性,以获取已设置的样式信息,添加我的 EventSetter 并将新样式应用于 Control代码>.

I wasn't able to edit the style, as it gets sealed once it is set. So I used the BasedOn property on a new style object, to get the already set style information, add my EventSetters and apply the new style to the Control.