[WPF]获取鼠标指针下的元素

原文: [WPF]获取鼠标指针下的元素

                                             [WPF]获取鼠标指针下的元素

                                                        周银辉

以前写过一些GetElementUnderMouse之类的函数,要用到坐标换算而显得有些麻烦(特别是当元素有XXXTransform的时候)

今天看到Mouse类居然有一个DirectlyOver属性,可以获得鼠标下的元素, 很奇怪,我的MSDN文档以及VS2008智能提示中都没有显示该属性,但反编译一下可以看到。

但必须注意到的一点是,WPF控件是由各个元素复合而成的,但Mouse类可不知道这概念,所以不要期望它为了返回一个Button,其很可能会返回Button的visualTree中的TextBlock等,所以,如果我们加上如下的方法就完美了:

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

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

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

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9047044.html