[WPF] Gets the element under the mouse pointer

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.