2009-09-03 106 views
0

我試圖讓橡皮筋或套索類型選擇用戶想要選擇的列表框中的項目。我的列表框位於一個網格中,並且在網格中添加了一個控件,該控件在我要選擇的區域上繪製一個矩形。我試過打擊測試列表框項目,看看它們是否屬於矩形,但它們似乎都返回了它們沒有的東西。當爲這些項目查看VisualTreeHelper.GetDescendantBounds(就像我爲矩形獲取它的X,Y所做的那樣)時,它始終將X,Y作爲0,0返回給每個項目。我在做什麼錯誤的測試?WPF在列表框中實現橡皮筋類型選擇

回答

0

您可以使用此代碼獲取UIElements相對於另一個UIElement的位置和邊界。該代碼取自this post

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 

public static class UIHelper 
{ 
    public static Boolean GetUIElementCornersRelativTo(UIElement Base, 
               UIElement RelativeTo, 
               ref Point TopLeft, 
               ref Point BottomLeft, 
               ref Point BottomRight, 
               ref Point TopRight, 
               ref String Message) 
    { 
     try 
     { 
      if (Base == null) 
      { 
       throw new Exception("Base UIElement is null"); 
      } 
      if (RelativeTo == null) 
      { 
       throw new Exception("RelativTo UIElement is null"); 
      } 

      TopLeft = Base.TranslatePoint(new Point(0, 0), RelativeTo); 
      BottomLeft = Base.TranslatePoint(new Point(0, Base.RenderSize.Height), RelativeTo); 
      BottomRight = Base.TranslatePoint(new Point(Base.RenderSize.Width, Base.RenderSize.Height), RelativeTo); 
      TopRight = Base.TranslatePoint(new Point(Base.RenderSize.Width, 0), RelativeTo); 

      Message = "OK"; 
      return true; 
     } 
     catch (Exception ex) 
     { 
      Message = ex.Message; 
      return false; 
     } 
    } 
    public static Boolean GetPointRelativTo(UIElement Base, 
            UIElement RelativeTo, 
            Point ToProjectPoint, 
            ref Point Result, 
            ref String Message) 
    { 
     try 
     { 
      if (Base == null) 
      { 
       throw new Exception("Base UIElement is null"); 
      } 
      if (RelativeTo == null) 
      { 
       throw new Exception("RelativTo UIElement is null"); 
      } 

      if (ToProjectPoint == null) 
      { 
       throw new Exception("To project point is null"); 
      } 

      Result = Base.TranslatePoint(ToProjectPoint, RelativeTo); 

      Message = "OK"; 
      return true; 
     } 
     catch (Exception ex) 
     { 
      Message = ex.Message; 
      return false; 
     } 
    } 
}