HOW TO:取得 Visual 的位移
更新:2007 年 11 月
這些範例示範如何擷取視覺物件相對於其父代 (Parent)、任何祖系或子代 (Descendant) 的位移 (Offset) 值。
範例
下列範例顯示以 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 圖形轉譯概觀