Original: [WPF] Gets the element under the mouse pointer
[WPF] Gets the element under the mouse pointer
Zhou Banhui
Previously wrote a number of functions such as getelementundermouse, to use the coordinate conversion is a bit cumbersome (especially when the element has Xxxtransform)
See today Mouse class actually has a Directlyover property, can get the element under the mouse, very strange, my MSDN document and VS2008 Smart hints do not show this property, but the anti-compilation can be seen.
It is important to note, however, that WPF controls are composited by individual elements, but the mouse class is not aware of the concept, so do not expect it to return a button, which is likely to return TextBlock in the button's VisualTree, and so on, If we add the following method, it will be perfect:
Public StaticT findvisualparent<T>(UIElement Element)whereT:uielement
{
UIElement Parent=element;
while(Parent!= NULL)
{
var correctlytyped=Parent asT;
if(correctlytyped!= NULL)
{
returncorrectlytyped;
}
Parent=visualtreehelper.getparent (parent) asUIElement;
}
return NULL;
}
Combining the two, our Getelementundermouse method can be written as follows:
Public StaticT Getelementundermouse<T>() whereT:uielement
{
returnfindvisualparent<T>(Mouse.directlyover asUIElement);
}
[WPF] Gets the element under the mouse pointer