开发者

WPF Get element at specific coordinates

开发者 https://www.devze.com 2023-03-21 21:49 出处:网络
I haveLabels inside a Canvas, I need to get the开发者_高级运维 label that intersects with coordinates X,Y?

I have Labels inside a Canvas, I need to get the开发者_高级运维 label that intersects with coordinates X,Y?

Thanks!!


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消