首页 > Windows开发 > 详细

WPF 获取鼠标指针下的元素

时间:2021-04-06 12:50:15      阅读:17      评论:0      收藏:0      [点我收藏+]

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

WPF 获取鼠标指针下的元素

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!