WPF - 确定鼠标是否在 UIElement 上

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

WPF - Determining if Mouse Is Over a UIElement

wpfmouseuielement

提问by Brent Lamborn

I have some xaml markup that looks essentially like this:

我有一些 xaml 标记,基本上如下所示:

<Canvas x:Name="A">
     <Canvas x:Name="B"/>
</Canvas>

I want to determine if the mouse is over CanvasB.

我想确定鼠标是否在CanvasB 上。

When I click while my mouse is over Canvas B, Mouse.DirectlyOver returns Canvas A (as I expect). I then get a reference to Canvas B from Canvas A but when I check Canvas B's IsMouseOver property it returns false.

当我在鼠标悬停在画布 B 上时单击时,Mouse.DirectlyOver 返回画布 A(如我所料)。然后我从画布 A 获得对画布 B 的引用,但是当我检查画布 B 的 IsMouseOver 属性时,它返回 false。

What is the best way to determine if the mouse is over Canvas B given the xaml above?

鉴于上面的 xaml,确定鼠标是否在 Canvas B 上的最佳方法是什么?

回答by Andy

You can use the IsMouseOver property to determine if the mouse is over a given control or not:

您可以使用IsMouseOver 属性来确定鼠标是否在给定控件上:

if(this.B.IsMouseOver)
    DoSomethingNice();

While Mouse.DirectlyOvercan work, if the mouse is over a control contained by the Canvas, that control will be returned instead of the Canvasitself. IsMouseOverwill work properly even in this case.

虽然Mouse.DirectlyOver可以工作,但如果鼠标位于 包含的Canvas控件上,则将返回该控件而不是其Canvas本身。IsMouseOver即使在这种情况下也能正常工作。

回答by Akku

I found an answer here on SO that should help you: StackOverflow: WPF Ways to find controls

我在 SO 上找到了一个可以帮助你的答案:StackOverflow: WPF Ways to find controls

Just for reference:

仅供参考:

I was just searching for a way to find out if my Mouse is over my applications window at all, and I successfully found this out using:

我只是在寻找一种方法来确定我的鼠标是否完全位于我的应用程序窗口上,并且我成功地发现了这一点:

if (Mouse.DirectlyOver != null)
    DoSomethingNice();

While debugging Mouse.DirectlyOver it seemed to be that it should have found your Canvas B, as it looks for the topmost element - so your example should work. It didn't give me a dependency object, but I guess you could just compare it to your canvas using this is the codebehind (untested):

在调试 Mouse.DirectlyOver 时,它似乎应该找到你的 Canvas B,因为它寻找最顶层的元素 - 所以你的例子应该可以工作。它没有给我一个依赖对象,但我想你可以使用这是代码隐藏(未经测试)将它与你的画布进行比较:

if (Mouse.DirectlyOver == this.B)
    DoSomethingNice();