Search code examples
c#wpfcoordinate-systems

WPF Get element at specific coordinates


I have Labels inside a Canvas, I need to get the label that intersects with coordinates X,Y?

Thanks!!


Solution

  • 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
        }
    }