简体   繁体   English

在WPF中,如何在外部提供的元素上触发鼠标事件?

[英]In WPF, how can I trigger mouse events on externally provided elements?

This is the situation I'm working with: 我正在处理的情况是:

情况

What I want to achieve is that hover events are handled via the hover elements, while other mouse events are forwarded to the child elements of the underlying stack panel. 我要实现的是,悬停事件是通过hover元素处理的,而其他鼠标事件将转发到基础堆栈面板的子元素。 The problem with this is that these child elements are added to the stack panel from elsewhere and might have children of their own. 问题是这些子元素是从其他位置添加到堆栈面板的,并且可能具有自己的子元素。

After some research I identified these possible approaches: 经过研究,我确定了这些可能的方法:

  1. Use the InputHitTest method on the stack panel to identify the hit element, and use RaiseEvent on it to trigger the event handler. 使用堆栈面板上的InputHitTest方法来识别hit元素,并在其上使用RaiseEvent触发事件处理程序。 The problem with this is that the InputHitTest method only returns leafs in the UI tree. 问题在于InputHitTest方法仅返回UI树中的叶子。 I could try to manually bubble the event upwards, but I find this dirty enough to try and find another solution first. 我可以尝试手动将事件冒泡,但是我发现这很脏,可以尝试首先找到另一个解决方案。 The same goes for tunneling the event downwards from the stack panel to the hit leaf element. 将事件从堆栈面板向下挖掘到命中叶子元素的过程也是如此。
  2. Raise a preview event on the stack panel, that tunnels "naturally" to child controls. 在堆栈面板上引发一个预览事件,该事件“自然地”传送到子控件。 I tried this: 我尝试了这个:
MouseButtonEventArgs newArgs = new MouseButtonEventArgs(eventArgs.MouseDevice, eventArgs.Timestamp, eventArgs.ChangedButton);
newArgs.RoutedEvent = Mouse.PreviewMouseDownEvent;
hitElement.RaiseEvent(newArgs);

But it doesn't work as expected. 但是它没有按预期工作。 Am I doing something wrong? 难道我做错了什么? Is this actually possible? 这实际上可行吗?

  1. Simulating the trigger of the event on the stack panel using an IInvokeProvider . 使用IInvokeProvider在堆栈面板上模拟事件的触发。 I haven't looked at this in detail because I find it a little dirty as well. 我没有详细研究它,因为我也发现它有点脏。

So, is what I want actually possible, and so, how should I do it? 那么,我真正想要的是什么,那么,我应该怎么做呢?

I solved my problem by doing the following: 我通过执行以下操作解决了我的问题:

  • remove the hover elements 删除悬停元素
  • listen to PreviewMouseMove and MouseLeave events on the stack panel 在堆栈面板上监听PreviewMouseMove和MouseLeave事件
  • use GetPosition on the PreviewMouseMove eventArgs and evaluate manually whether the mouse is in the rectangular borders or not 在PreviewMouseMove eventArgs上使用GetPosition并手动评估鼠标是否在矩形边界内

It's shamefully simple really... 真的很可耻...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM