locked
VisualTreeHelper.FindElementsInHostCoordinates bug when XAML page size is defined

    Question

  • I have a red rectangle in my page

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Border x:Name="rectangle" Width="250" Height="250" Background="Red"/>
    </Grid>

    If I want to get a set of objects in my rectangle area I use

    var page = GetPage(this.rectangle);
    var transform = this.rectangle.TransformToVisual(page);
    var rect = transform.TransformBounds(new Rect(0, 0, rectangle.ActualWidth, rectangle.ActualHeight));
    var covers = VisualTreeHelper.FindElementsInHostCoordinates(rect, page, false);

    Where GetPage is my method retrieving the Page parent of the given element.

    The solution works fine unless the Width and Height of the page are specified in XAML. Then the covers no longer contain the red rectangle.

    I found that if I set the third argument of the FindElementsInHostCoordinates to true, the result is as expected again. This makes no sense to me, since the argument only specifies whether or not to include invisible and non hit-testable objects. I've double checked IsHitTestVisible and Visibility properties of the rectangle. It is both visible and hit-testable.

    Monday, May 12, 2014 6:22 AM

Answers

  • Hi, I think the transform is not correct when the Width and Height of the page are specified, you can try to transform to Window.Current.Content:

    var transform = this.rectangle.TransformToVisual(Window.Current.Content);
    var rect = transform.TransformBounds(new Rect(0, 0, rectangle.ActualWidth, rectangle.ActualHeight));
    var covers = VisualTreeHelper.FindElementsInHostCoordinates(rect, page, false);

    Monday, May 12, 2014 7:11 AM

All replies

  • Hi, I think the transform is not correct when the Width and Height of the page are specified, you can try to transform to Window.Current.Content:

    var transform = this.rectangle.TransformToVisual(Window.Current.Content);
    var rect = transform.TransformBounds(new Rect(0, 0, rectangle.ActualWidth, rectangle.ActualHeight));
    var covers = VisualTreeHelper.FindElementsInHostCoordinates(rect, page, false);

    Monday, May 12, 2014 7:11 AM
  • Hi lapheal, thanks for the idea. It seems to be working correctly for most cases I can think of. I am just wondering, is it possible that the Window.Current.Content will be set to some UIElement that is not TransformToVisual compatible?
    Monday, May 12, 2014 12:57 PM