如何:获取 Visual 的偏移量
这些示例展示如何检索与父级或任何原型或后代相关的视觉对象的偏移值。
示例
以下标记示例显示了使用 Margin 值 4 定义的 TextBlock。
<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 方法。
获取与原型相关的偏移
以下标记示例显示两个 StackPanel 对象中嵌套的 TextBlock。
<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 方法检索与包含 Window 相关的 TextBlock 的偏移。 偏移值包含在返回的 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))
偏移考虑包含 Window 中所有对象的 Margin 值。 在这种情况下,X 为 28 (16 + 8 + 4),Y 为 28。
返回的偏移值与 Visual 的原型相关。 如果要返回与 Visual 的后代相关的偏移值,请使用 TransformToDescendant 方法。
获取与后代相关的偏移
以下标记示例显示 StackPanel 对象中包含的 TextBlock。
<StackPanel Name="myStackPanel" Margin="8">
<TextBlock Name="myTextBlock" Margin="4" Text="Hello, world" />
</StackPanel>
以下代码示例显示如何使用 TransformToDescendant 方法检索与子级 TextBlock 相关的 StackPanel 的偏移。 偏移值包含在返回的 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。 偏移值是负值,因为父级对象相对于子级对象是负偏移。
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈