How to: Get the Offset of a Visual
These examples show how to retrieve the offset value of a visual object that is relative to its parent, or any ancestor or descendant.
The following markup example shows a TextBlock that is defined with Margin value of 4.
The following code example shows how to use the GetOffset method to retrieve the offset of the TextBlock. The offset values are contained within the returned Vector value.
The offset takes into account the Margin value. In this case, X is 4, and Y is 4.
The returned offset value is relative to the parent of the Visual. If you want to return an offset value that is not relative to the parent of a Visual, use the TransformToAncestor method.
Getting the Offset Relative to an Ancestor
The following markup example shows a TextBlock that is nested within two StackPanel objects.
The following illustration shows the results of the markup.
The following code example shows how to use the TransformToAncestor method to retrieve the offset of the TextBlock relative to the containing Window. The offset values are contained within the returned GeneralTransform value.
The offset takes into account the Margin values for all objects within the containing Window. In this case, X is 28 (16 + 8 + 4), and Y is 28.
The returned offset value is relative to the ancestor of the Visual. If you want to return an offset value that is relative to the descendant of a Visual, use the TransformToDescendant method.
Getting the Offset Relative to a Descendant
The following markup example shows a TextBlock that is contained within a StackPanel object.
The following code example shows how to use the TransformToDescendant method to retrieve the offset of the StackPanel relative to its child TextBlock. The offset values are contained within the returned GeneralTransform value.
The offset takes into account the Margin values for all objects. In this case, X is -4, and Y is -4. The offset values are negative values, since the parent object is negatively offset relative to its child object.