2009-09-03 105 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; 
     } 
    } 
}