此段示例在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(0, 0));