wpf WPF在鼠标下获取元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45813/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:35:51  来源:igfitidea点击:

WPF Get Element(s) under mouse

wpfelementvisualtreehelpervisual-tree

提问by NotDan

Is there a way with WPF to get an array of elements under the mouse on a MouseMove event?

WPF 有没有办法在 MouseMove 事件上获取鼠标下的元素数组?

回答by Andy

You can also try using the Mouse.DirectlyOver property to get the top-most element that is under the mouse.

您还可以尝试使用 Mouse.DirectlyOver 属性来获取鼠标下方的最顶部元素。

回答by David Schmitt

From "WPF Unleashed", page 383:

来自“ WPF Unleashed”,第 383 页:

Visual hit testing can inform you about allVisuals that intersect a location, [...] you must use [...] the [VisualTreeHelper.]HitTestmethod that accepts a HitTestResultCallbackdelegate. Before this version of HitTestreturns, the delegate is invoked once for each relevant Visual, starting from the topmost and ending at the bottommost.

视觉命中测试可以告知您与某个位置相交的所有Visuals,[...] 您必须使用 [...][VisualTreeHelper.]HitTest接受HitTestResultCallback委托的 方法 。在此版本HitTest返回之前,为每个相关的 调用一次委托Visual,从最顶部开始到最底部结束。

The signature of such a callback is

这种回调的签名是

HitTestResultBehavior Callback(HitTestResult result)

and it has to return HitTestResultBehaviour.Continueto receive further hits, as shown below (from the linked page on MSDN):

它必须返回HitTestResultBehaviour.Continue以接收更多点击,如下所示(来自 MSDN 上的链接页面):

// Return the result of the hit test to the callback.
public HitTestResultBehavior MyHitTestResult(HitTestResult result)
{
    // Add the hit test result to the list that will be processed after the enumeration.
    hitResultsList.Add(result.VisualHit);

    // Set the behavior to return visuals at all z-order levels.
    return HitTestResultBehavior.Continue;
}

For further information, please consult the MSDN documentation for VisualTreeHelper.HitTest.

有关详细信息,请参阅MSDN 文档中的VisualTreeHelper.HitTest.