Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindElementsInHostCoordinates Relative To Control Space Not Entire Page

I'm using the VisualTreeHelper method FindElementsInHostCoordinates to find a ListBoxItem at the given X and Y location. However, X and Y value appear to be related to points in the entire page not just the ListBox I'm interested in (even though I'm passing in that element into the subtree parameter of the method). Below, this refers to a custom control which derives from ListBox.

foreach (UIElement element in VisualTreeHelper.FindElementsInHostCoordinates(new Point(X, Y), this))
{
    if (element is ListBoxItem)
    {
        int index = this.ItemContainerGenerator.IndexFromContainer(element);
        break;
    }
}

So, (0,0) would be relative to the top left corner of the entire plug-in not the top left corner of the ListBox. Do I need to do some mathematical work here myself (in code) to transform the page coordinates to the ListBox coordinates or is there some other way to do a hit test to tell if a given X and Y point is over a ListBoxItem?

Thanks.

like image 841
beaudetious Avatar asked Feb 04 '10 15:02

beaudetious


1 Answers

I figured this out myself (wow). I determined the top and left values for my control and then added the X and Y values internal to my control:

GeneralTransform gt = this.TransformToVisual(Application.Current.RootVisual as UIElement);
Point offset = gt.Transform(new Point(0, 0));
double controlTop = offset.Y + Y;
double controlLeft = offset.X + X;

So, I can pass in X and Y values relative to my control, but this code will transform it to global coordinates.

Works for me and hey!, no tumbleweed badge on this question. :)

like image 70
beaudetious Avatar answered Sep 20 '22 20:09

beaudetious