Reputation:
I have Labels inside a Canvas, I need to get the label that intersects with coordinates X,Y?
Thanks!!
Upvotes: 5
Views: 7189
Reputation: 11230
Canvas.GetLeft(element), Canvas.GetTop(element) will get you any element's position. Use ActualWidth and ActualHeight to form its complete rectangle. You can iterate through the Children of the Canvas with a foreach.
Edit: CodeNaked pointed out that elements might be set with SetRight or SetBottom so I modified the sample code:
foreach (FrameworkElement nextElement in myCanvas.Children)
{
double left = Canvas.GetLeft(nextElement);
double top = Canvas.GetTop(nextElement);
double right = Canvas.GetRight(nextElement);
double bottom = Canvas.GetBottom(nextElement);
if (double.IsNaN(left))
{
if (double.IsNaN(right) == false)
left = right - nextElement.ActualWidth;
else
continue;
}
if (double.IsNaN(top))
{
if (double.IsNaN(bottom) == false)
top = bottom - nextElement.ActualHeight;
else
continue;
}
Rect eleRect = new Rect(left, top, nextElement.ActualWidth, nextElement.ActualHeight);
if (myXY.X >= eleRect.X && myXY.Y >= eleRect.Y && myXY.X <= eleRect.Right && myXY.Y <= eleRect.Bottom)
{
// Add to intersects list
}
}
Upvotes: 3
Reputation: 41253
Simply use InputHitTest
on your canvas, passing the coordinate you want as parameter. Note that InputHitTest
is available on every UIElement
and is not specific to canvas.
Upvotes: 7