转换X,Y坐标 [英] Translating X,Y Coordinate
问题描述
我目前有一个用户控件,其中包含具有一定X,Y坐标的项目,并且这些点必须位于其中是有限制的.在这种情况下,这些位置是0> X> 40和0> Y> 80(40x80).我在其中托管这些项目的控件是动态的,但基于窗口大小具有一定的宽高比.我需要翻译那些X& Y坐标到用户控件内的相对位置.非常感谢您的帮助!提前致谢!如果有帮助,我正在使用Silverlight.
I currently have a user control that contains items that have a certain X, Y coordinate and there are limits to what those points must be within. In this case those positions are 0 > X > 40 and 0 > Y > 80 (40x80). The control I am hosting those items in is dynamic but has a certain aspect ratio based on window size. I need to translate those X & Y coordinates into relative locations within the user control. Any help is greatly apprecaited! Thanks in advance! If it matters/helps, I'm using Silverlight.
推荐答案
,您可以使用GeneralTransform来确定UIElement相对于容器的位置.这是一个片段:
you can use GeneralTransform to determine a UIElement's position relative to a container. Here's a snippet:
/// <summary>
/// Gets the position of the specified element's top left corner, relative to the specified container.
/// </summary>
/// <param name="element"></param>
/// <param name="container"></param>
public static Point GetPosition(UIElement element, UIElement container)
{
if (element == null)
throw new ArgumentNullException("element");
if (container == null)
throw new ArgumentNullException("container");
var gt = element.TransformToVisual(container);
var position = gt.Transform(new Point(0, 0));
return position;
}
干杯,亚历克斯
实际上,不需要检查容器"是否为null-TransformToVisual还将接受null作为参数. 另一个问题:TransformToVisual将抛出ArgumentException例如当元素"不可见时,当前不在可视树等中. 不幸的是,在实际调用"element"之前,我找不到确定TransformToVisual是否会抛出该异常的方法.因此,我只是简单地将对TransformToVisual的调用包装在try-catch块中并吞下ArgumentException,因为恕我直言,这是毫无用处的.
In fact, checking "container" for null is unnecessary - TransformToVisual will also accept null as parameter. Another issue: TransformToVisual will throw an ArgumentException e.g. when "element" is not visible, is currently not in the visual tree etc. etc. Unfortunately, I could not find a way to determine whether TransformToVisual will throw that exception before actually calling it on "element". So I simply wrapped calls to TransformToVisual in a try-catch block and swallowed the ArgumentException, because it is quite useless anyway IMHO.
这篇关于转换X,Y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!