How to get the absolute position of an element?
Asked Answered
L

1

18

Assume something simple like:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="300" />
        <ColumnDefinition Width="300" />
    </Grid.ColumnDefinitions>

    <TextBlock Name="MainTextBlock" Grid.Column="1" Text="Hello" />
</Grid>

How can I get the absolute position of MainTextBlock?

Lerner answered 12/9, 2012 at 11:45 Comment(5)
Do you mean position relative to window, grid or user screen? Relative to grid, you can get or set Margin property; in canvas - Top and Left properties.Technetium
you have to manually calculate control's position, read here blogs.msdn.com/b/llobo/archive/2006/05/02/…Technetium
I'm afraid there is no "DllImport" in WinRT.Lerner
Just follow the theory: first find position within window and then find window's position on the screen. Make subtraction and you will get result. Can u explain the reason why you need absolute position of a control?Technetium
If the accepted answer does not work in your project (like for me) you can write a loop which sums up the ActualOffset of the UIElement and it's parent, grandparent, etc up to the root element.Hangbird
R
56

I think this will work...

var ttv = MainTextBlock.TransformToVisual(Window.Current.Content);
Point screenCoords = ttv.TransformPoint(new Point(0, 0));
Rebate answered 12/9, 2012 at 12:49 Comment(3)
Thx,it's help me to write my application that need a cur and know it's position. But when the control in the page in MainPage.Frame that can get the position ?Trondheim
Sadly this does not work inside a Xaml Island project.Hangbird
Won't work with FlowDirection = RightToLeftDorseydorsiferous

© 2022 - 2024 — McMap. All rights reserved.