WPF 获取鼠标指针下的元素

Mouse类有一个DirectlyOver属性,可以获得鼠标下的元素。

但是WPF 控件是由各个元素复合而成的,Mouse类可不知道这概念。

所以不要期望它会返回一个Button,其很可能会返回Button的visualTree中的TextBlock等,所以,如果我们加上如下的方法就完美了:

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

两者结合一下,我们的GetElementUnderMouse方法便可以如下书写:

public static T GetElementUnderMouse<T>() where T: UIElement
{
    return FindVisualParent<T>(Mouse.DirectlyOver as UIElement);
}

原文链接:https://www.cnblogs.com/zhouyinhui/archive/2010/07/28/1786775.html

原文地址:https://www.cnblogs.com/flamegreat/p/14620681.html