此段示例在MSDN中可见。XAML代码如下:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<StackPanel Margin="16">
<StackPanel Margin="8">
<TextBlock Name="myTextBlock" Margin="4" Text="Hello, world" />
</StackPanel>
</StackPanel>
</Window>
1、如果只需要获取相对于其父级的偏移量,则可以使用以下方法:
// Return the offset vector for the TextBlock object.
Vector vector = VisualTreeHelper.GetOffset(myTextBlock); // Convert the vector to a point value.
Point currentPoint = new Point(vector.X, vector.Y);
偏移量保存在Vector对象中
2、相对灵活的方法可以使用 TransformToAncestor方法,这样可以获得相对于Window的偏移量
// Return the general transform for the specified visual object.
GeneralTransform generalTransform1 = myTextBlock.TransformToAncestor(this); // Retrieve the point value relative to the parent.
Point currentPoint = generalTransform1.Transform(new Point(, ));