4

It seems that all of the way of retrieving an element under the Mouse relates to Visual Hit testing.

Is there some mechanism that I'm missing which would allow me to grab the actual UIElement that represents the current visual tree that the HitTest returns?

Summary of what I'm doing:

I have a custom tooltip class which relies on doing something based on the UIElement that the mouse is over.

Simply put, it hooks into the owning Window's PreviewMouseMove event and updates a "current Item". This current item should represent the UIElement that the mouse is currently over top of.

Unfortunately everything I've encountered with Mouse.DirectlyOver, VisualTreeHelper.HitTest (callbacks included) doesn't work.

Can anyone offer insight in how to accomplish a seemingly simple task in WPF within Window's MouseMove event?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
tronious
  • 1,547
  • 2
  • 28
  • 45

2 Answers2

7

Use the Mouse.DirectlyOver property:

var UIElement = Mouse.DirectlyOver as UIElement;
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
  • 1
    This still grabs visual elements though. So for example...if I were to mouseover a "Button" with it's default template, if I placed the mouse of the text (content) it would return to me that specific textblock. I basically want it to return the Button as opposed to the individual visual element. – tronious May 13 '13 at 16:55
2

I don't know any explicit way, but the idea is pretty simple,

1) Find the visual tree element

2) Test if the element is present in logical tree,

3) If it's present, you've found the answer.

4) Otherwise you're gonna have to call VisualTreeHelper.GetParent() and continue the algorithm.

Ps, LogicalTreeHelper.GetParent(your visual tree element) MIGHT also work.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Erti-Chris Eelmaa
  • 25,338
  • 6
  • 61
  • 78