在下列標記範例中,示範了包含在 StackPanel 物件中的 TextBlock

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

在下列程式碼範例中,示範了如何使用 TransformToVisual 方法,擷取 StackPanel 相對於其子 TextBlock 的位移。位移值含在傳回的 GeneralTransform 值中。

// 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。位移值是負值,因為父物件相對於其子物件的位移是負的。

 

若取myStackPanel相对于 应用程序左上角的  绝对位置,如下:

// Return the general transform for the specified visual object.
GeneralTransform generalTransform1 = myStackPanel.TransformToVisual(null);

// Retrieve the point value relative to the child.
Point currentPoint = generalTransform1.Transform(new Point(0, 0));

posted on 2010-01-12 11:35  湛然常寂  阅读(1716)  评论(1编辑  收藏  举报