这些示例展示如何检索与父级或任何原型或后代相关的视觉对象的偏移值。
示例:
以下标记示例显示了使用 TextBlock 值 4 定义的 Margin。
<TextBlock Name="myTextBlock" Margin="4" Text="Hello, world" />
下面的代码示例演示如何使用 GetOffset 方法检索 TextBlock的偏移量。 偏移值包含在返回的 Vector 值内。
// 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);
' Return the offset vector for the TextBlock object.
Dim vector As Vector = VisualTreeHelper.GetOffset(myTextBlock)
' Convert the vector to a point value.
Dim currentPoint As New Point(vector.X, vector.Y)
偏移考虑 Margin 值。 在这种情况下,X 为 4,Y 为 4。
返回的偏移值与 Visual 的父级相关。 如果要返回与 Visual 的父级无关的偏移值,请使用 TransformToAncestor 方法。
获取与原型相关的偏移
以下标记示例显示两个 TextBlock 对象中嵌套的 StackPanel。
<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>
下图显示了标记的结果。
两个 StackPanel 中嵌套的 TextBlock
下面的代码示例演示如何使用 TransformToAncestor 方法检索相对于包含 TextBlock的 Window 偏移量。 偏移值包含在返回的 GeneralTransform 值内。
// 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));
' Return the general transform for the specified visual object.
Dim generalTransform1 As GeneralTransform = myTextBlock.TransformToAncestor(Me)
' Retrieve the point value relative to the parent.
Dim currentPoint As Point = generalTransform1.Transform(New Point(0, 0))
偏移考虑包含 Margin 中所有对象的 Window 值。 在这种情况下,X 为 28(16 + 8 + 4),Y 为 28。
返回的偏移值与 Visual 的原型相关。 如果要返回与 Visual 的后代相关的偏移值,请使用 TransformToDescendant 方法。
获取与后代相关的偏移
以下标记示例显示 TextBlock 对象中包含的 StackPanel。
<StackPanel Name="myStackPanel" Margin="8">
<TextBlock Name="myTextBlock" Margin="4" Text="Hello, world" />
</StackPanel>
下面的代码示例演示如何使用 TransformToDescendant 方法检索相对于其子 StackPanel的 TextBlock 偏移量。 偏移值包含在返回的 GeneralTransform 值内。
// Return the general transform for the specified visual object.
GeneralTransform generalTransform1 = myStackPanel.TransformToDescendant(myTextBlock);
// Retrieve the point value relative to the child.
Point currentPoint = generalTransform1.Transform(new Point(0, 0));
' Return the general transform for the specified visual object.
Dim generalTransform1 As GeneralTransform = myStackPanel.TransformToDescendant(myTextBlock)
' Retrieve the point value relative to the child.
Dim currentPoint As Point = generalTransform1.Transform(New Point(0, 0))
偏移考虑所有对象的 Margin 值。 在这种情况下,X 为 -4,Y 为 -4。 偏移值为负值,因为父对象相对于其子对象向负方向偏移。