2010-01-13 13 views
7

Tôi muốn thực hiện kiểm tra hit hình chữ nhật trên thành phần Canvas WPF để có được các Điều khiển bị chồng chéo bởi phần tử khung hình chữ nhật. Tôi đã tìm thấy phương thức VisualTreeHelper.FindElementsInHostCoordinates của Silverlight, nhưng dường như nó không có sẵn trong WPF.FindElementsInHostCoordinates tương đương của Silverlight trong WPF là gì?

Phương pháp nào tốt nhất để đạt được chức năng như vậy?

Trả lời

3

Tương đương gần nhất là VisualTreeHelper.HitTest. Nó hoạt động rất khác với Silverlight's FindElementsInHostCoordinates, nhưng bạn sẽ có thể sử dụng nó cho nhu cầu của bạn.

3

Giả sử bạn có một cuộc gọi như thế này trong Silverlight

var result = VisualTreeHelper.FindElementsInHostCoordinates(myPoint, myUIElement); 

sau đó mã WPF này nên có một tương đương result

var result = new List<DependencyObject>(); 
         //changed from external edits, because VisualHit is 
         //only a DependencyObject and may not be a UIElement 
         //this could cause exceptions or may not be compiling at all 
         //simply filter the result for class UIElement and 
         //cast it to IEnumerable<UIElement> if you need 
         //the very exact same result including type 

VisualTreeHelper.HitTest(
    myUiElement, 
    null, 
    new HitTestResultCallback(
     (HitTestResult hit)=>{ 
      result.Add(hit.VisualHit); 
      return HitTestResultBehavior.Continue; 
     }), 
    new PointHitTestParameters(myPoint)); 

trong trường hợp đặc biệt, bạn có thể muốn sử dụng GeometryHitTestParameters thay vì PointHitTestParameters để làm một bài kiểm tra Rect-Test.