WPF获取特定坐标的元素(WPF Get element at specific coordinates)

我在Canvas中有标签,我需要获得与坐标X,Y相交的标签?

谢谢!!

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

Thanks!!

最满意答案

Canvas.GetLeft(element),Canvas.GetTop(element)会得到你任何元素的位置。 使用ActualWidth和ActualHeight组成其完整的矩形。 您可以使用foreach遍历Canvas中的Children。

编辑: CodeNaked指出,可能使用SetRight或SetBottom设置元素,所以我修改了示例代码:

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

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

更多推荐

标签,Canvas,电脑培训,计算机培训,IT培训"/> <meta name="description" c