在 WPF 中获取鼠标下的逻辑 UIElement
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16525774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the Logical UIElement under the mouse in WPF
提问by tronious
It seems that all of the way of retrieving an element under the Mouse relates to Visual Hit testing.
似乎所有在鼠标下检索元素的方式都与 Visual Hit 测试有关。
Is there some mechanism that I'm missing which would allow me to grab the actual UIElementthat represents the current visual tree that the HitTestreturns?
是否有一些我缺少的机制可以让我获取UIElement代表HitTest返回的当前可视化树的实际值?
Summary of what I'm doing:
我正在做的事情的总结:
I have a custom tooltip class which relies on doing something based on the UIElement that the mouse is over.
我有一个自定义工具提示类,它依赖于基于鼠标悬停的 UIElement 执行某些操作。
Simply put, it hooks into the owning Window's PreviewMouseMoveevent and updates a "current Item". This current item should represent the UIElementthat the mouse is currently over top of.
简单地说,它挂钩到拥有窗口的PreviewMouseMove事件并更新“当前项目”。此当前项目应代表UIElement鼠标当前位于其上方的项目。
Unfortunately everything I've encountered with Mouse.DirectlyOver, VisualTreeHelper.HitTest(callbacks included) doesn't work.
不幸的是,我遇到的所有Mouse.DirectlyOver, VisualTreeHelper.HitTest(包括回调)都不起作用。
Can anyone offer insight in how to accomplish a seemingly simple task in WPF within Window's MouseMoveevent?
任何人都可以提供有关如何在 Window 的MouseMove事件中在 WPF 中完成看似简单的任务的见解吗?
回答by Federico Berasategui
Use the Mouse.DirectlyOverproperty:
使用Mouse.DirectlyOver属性:
var UIElement = Mouse.DirectlyOver as UIElement;
回答by Erti-Chris Eelmaa
I don't know any explicit way, but the idea is pretty simple,
我不知道任何明确的方法,但这个想法很简单,
1) Find the visual tree element
1) 找到可视化树元素
2) Test if the element is present in logical tree,
2) 测试元素是否存在于逻辑树中,
3) If it's present, you've found the answer.
3) 如果它存在,你就找到了答案。
4) Otherwise you're gonna have to call VisualTreeHelper.GetParent()and continue the algorithm.
4)否则你将不得不调用VisualTreeHelper.GetParent()并继续算法。
Ps, LogicalTreeHelper.GetParent(your visual tree element)MIGHT also work.
Ps,可能LogicalTreeHelper.GetParent(your visual tree element)也有效。

