Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Determining if Mouse Is Over a UIElement

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 (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.

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

like image 207
Brent Lamborn Avatar asked Dec 03 '10 16:12

Brent Lamborn


2 Answers

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.

like image 140
Andy Avatar answered Oct 18 '22 05:10

Andy


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();
like image 31
Akku Avatar answered Oct 18 '22 04:10

Akku