首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WPF 獲取鼠標指標下元素的最佳實踐:Mouse.DirectlyOver 與視覺樹遍歷

     編輯:關於.NET

痛點與發現

以往寫 GetElementUnderMouse 需座標轉換,遇元素有 Transform 更麻煩。今日發現 Mouse 類有 DirectlyOver 屬性可直接獲取鼠標下元素,但 MSDN 文檔與 VS 2008 IntelliSense 均未顯示,反編譯才可見。

陷阱:WPF 控件為組合元素

WPF 控件由多元素組合 (如 Button 含 TextBlock),Mouse.DirectlyOver 可能返回內部元素 (TextBlock) 而非控件本身 (Button)。

完美解法:結合視覺樹向上查找

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

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

兩者結合,GetElementUnderMouse<Button>() 即可精準獲取鼠標下的 Button,而非其內部 TextBlock。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved