WPF - Determining if Mouse Is Over a UIElement

Brent Lamborn picture Brent Lamborn · Dec 3, 2010 · Viewed 28.9k times · Source

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?

Answer

Andy picture Andy · Feb 21, 2013

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.