且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF获取某控件的位置,也就是偏移量

更新时间:2022-09-21 17:39:19

原文:WPF获取某控件的位置,也就是偏移量

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