如何:获取 Visual 的偏移量

更新:2007 年 11 月

这些示例演示如何检索可视化对象相对于其父级、上级或子代的偏移量值。

示例

下面的标记示例演示了一个使用 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);

偏移量考虑了 Margin 值。在此例中,X 是 4,Y 也是 4。

返回的偏移量值相对于 Visual 的父级。如果要让返回的偏移量值不相对于 Visual 的父级,请使用 TransformToAncestor 方法。

获取相对于上级的偏移量

下面的标记示例演示了嵌套在两个 StackPanel 对象中的 TextBlock

<Window xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://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));

偏移量考虑了包含 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 方法检索 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));

偏移量考虑了所有对象的 Margin 值。在此例中,X 是 -4,Y 也是 -4。因为父对象相对于其子对象进行了负偏移,所以偏移量值为负值。

请参见

概念

Windows Presentation Foundation 图形呈现概述

参考

Visual

VisualTreeHelper