开发者

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!!


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜