游路

-言或自生天趣,事当曲尽人情
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

计算控件之间的相对位置

Posted on 2011-11-15 13:45  游路  阅读(233)  评论(0)    收藏  举报

下面的标记示例演示了 StackPanel 对象中包含的 TextBlock

<StackPanel Name="myStackPanel" Margin="8">
<TextBlock Name="myTextBlock" Margin="4" Text="Hello, world"/>
</StackPanel>


下面的代码示例演示如何使用 TransformToVisual 方法检索 StackPanel 相对于其子级 TextBlock 的偏移量。 偏移量值包含在返回的 GeneralTransform 值内。

VB

' Return the general transform for the specified visual object. 
Dim generalTransform1 As GeneralTransform = myStackPanel.TransformToVisual(myTextBlock)
' Retrieve the point value relative to the child.
Dim currentPoint As Point = generalTransform1.Transform(New Point(0, 0))
 
C#
// Return the general transform for the specified visual object.
GeneralTransform generalTransform1 = myStackPanel.TransformToVisual(myTextBlock);
// Retrieve the point value relative to the child.
Point currentPoint = generalTransform1.Transform(new Point(0, 0));

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

参考:http://msdn.microsoft.com/zh-cn/site/system.windows.media.visual.transformtovisual