开发者

WPF - Determining if Mouse Is Over a UIElement

开发者 https://www.devze.com 2023-01-28 14:02 出处:网络
I have some xaml markup that looks essentially like this: <Canvas x:Name=\"A\"> <Canvas x:Name=\"B\"/>

I have some xaml markup that looks essentially like this:

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

I want to determine if the mouse is over Canvas B.

When I click while my mouse is over Canvas B, Mouse.DirectlyOver returns Canvas A (a开发者_高级运维s 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.

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


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

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

While Mouse.DirectlyOver can work, if the mouse is over a control contained by the Canvas, that control will be returned instead of the Canvas itself. IsMouseOver will work properly even in this case.


I found an answer here on SO that should help you: 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):

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


Here you can find from mouse click event with hit test.

{
            Point pt = e.GetPosition((UIElement)sender);

            // Perform the hit test against a given portion of the visual object tree.
            HitTestResult result = VisualTreeHelper.HitTest(this.B, pt);

            if (result != null)
            {
                // Perform action on hit visual object.              
            }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消