views:

331

answers:

1

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.

+2  A: 

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. :)

beaudetious
You might consider using the unadorned "silverlight" tag in your future questions, it gets more eyeballs.
AnthonyWJones
Thanks for the tip. Chalk up another on to the devil's in the details. :)
beaudetious