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.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With