It is a little bit unintuitive to do this, but it can be done. It is a two step process. First, what you want to use the TransformToVisual
function (from MSDN):
Returns a transform object that can be used to transform coordinates from the UIElement to the specified object.
TransformToVisual
will yield a GeneralTransform
that will perform the transformation from any UIElement to any other UIElement (given that they both exist in the same visual tree). It sounds like what you want is the transformation from the RootVisual
.
var transform = Application.RootVisual.TransformToVisual(myUiElement);
The transform
object is now a general transformation that can be used to transform anything in the same way that myUiElement
was transformed relative to RootVisual
The next step is to transform a point using that transformation.
var myUiElementPosition = transform.Transform(new Point(0,0));
The myUiElementPosition
is now a Point
that has been transformed and should be the position of the UIElement
you're looking for. new Point(0,0)
is used because I assume you want to have the position given relative to the top left corner of the RootVisual
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…