Get the element under the mouse pointer in WPF

Source: Internet
Author: User

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);
         }

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.