我有一个 UIElement,它执行了各种转换(缩放和平移)。
有没有办法在转换后获取 UIElement 的位置?我试过 GetValue(Canvas.TopProperty)
但它并没有改变它加载的内容。
我一定是遗漏了一些明显但不确定是什么的东西。 (我正在使用银光)
最佳答案
这样做有点不直观,但可以做到。这是一个两步过程。首先,您要使用 TransformToVisual
函数 (from MSDN):
Returns a transform object that can be used to transform coordinates from the UIElement to the specified object.
TransformToVisual
将生成一个 GeneralTransform
,它将执行从任何 UIElement 到任何其他 UIElement 的转换(假定它们都存在于同一可视化树中)。听起来您想要的是 RootVisual
的转换。
var transform = Application.RootVisual.TransformToVisual(myUiElement);
transform
对象现在是一个通用的转换,可以用来转换任何东西,就像 myUiElement
相对于 RootVisual
进行转换一样
下一步是使用该变换来变换一个点。
var myUiElementPosition = transform.Transform(new Point(0,0));
myUiElementPosition
现在是一个经过转换的Point
,应该是您要查找的UIElement
的位置。使用 new Point(0,0)
是因为我假设您希望相对于 RootVisual
的左上角给定位置。
关于c# - 变换后获取元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5266506/