Previously wrote a number of functions such as getelementundermouse, to use the coordinate conversion and appear to be a bit of trouble (especially when the element has Xxxtransform)
Today I see that the mouse class actually has a directlyover attribute that can get the elements under the mouse, and it's strange that this attribute is not shown in my MSDN documentation and VS2008 Smart hints, but it can be seen in reverse compilation.
However, it is important to note that the WPF control is compounded by various elements, but the mouse class does not know the concept, so do not expect it to return a button that is likely to return the TextBlock in the button's VisualTree, so If we add the following method to perfection:
public static T FindVisualParent<T>(UIElement element) where T : UIElement
{
UIElement parent = element;
while (parent != null)
{
var correctlyTyped = parent as T;
if (correctlyTyped != null)
{
return correctlyTyped;
}
parent = VisualTreeHelper.GetParent(parent) as UIElement;
}
return null;
}
Combining the two, our Getelementundermouse method can be written as follows:
public static T GetElementUnderMouse<T>() where T: UIElement
{
return FindVisualParent<T> (Mouse.DirectlyOver as UIElement);
}