Page 1 of 1

Get and set the absolute position of TextBlock by code

Posted: 15 Dec 2018, 12:24
by elecman
I want to set (or at least get) the position of a TextBlock in Unity. The XAML code looks something like this:
<TextBlock Name="speed_B" Text="320" FontFamily="#Arial" FontSize="43.2121532069983" Foreground="White" Canvas.Left="16.8453794565401" Canvas.Top="391.239437196062"/>
I can set the position using TranslateTransform but the start position is always 0. This makes it very difficult to do absolute positioning if I can't at least get the absolute start position. I suppose I need access to Canvas.Left and Canvas.Top from TextBlock, but the API does not allow that.

I must add that the XAML code is not handwritten so I can't manually modify it, as that is too much work. It is automatically generated by a conversion form Inkscape SVG to XAML using ViewerSVG.

Re: Get and set the absolute position of TextBlock by code

Posted: 17 Dec 2018, 12:08
by sfernandez
To get the absolute position in screen of any UI element you can use PointToScreen function passing (0,0) as initial point:
Point pos = element.PointToScreen(new Point(0, 0));
Is that what you need?

Re: Get and set the absolute position of TextBlock by code

Posted: 18 Dec 2018, 11:39
by elecman
That function returns 0,0 unfortunately.

Re: Get and set the absolute position of TextBlock by code

Posted: 18 Dec 2018, 13:30
by sfernandez
To get a meaningful value for that function you should wait until the xaml layout is finished, you can do that in the Loaded event, or call element.UpdateLayout().
Once layout is done, an element can't return 0,0 if its bounding box is not positioned in the top-left corner of the screen.

I did a simple test in Unity and it works as expected:
<Grid
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <TextBlock x:Name="txt" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,400,0" Text="Hello World!"/>
</Grid>
public class TestBehavior : MonoBehaviour
{
    private void Start()
    {
        NoesisView view = GetComponent<NoesisView>();
        TextBlock txt = (TextBlock)view.Content.FindName("txt");
        Debug.Log("Start: " + txt.PointToScreen(new Point(0,0))); // this prints 0,0
        view.Content.Loaded += (s, e) =>
        {
            Debug.Log("Loaded: " + txt.PointToScreen(new Point(0, 0))); // this prints the right value
        };
    }
}

Re: Get and set the absolute position of TextBlock by code

Posted: 20 Dec 2018, 23:02
by elecman
Thanks, that worked.

Re: Get and set the absolute position of TextBlock by code

Posted: 24 Dec 2018, 12:06
by sfernandez
Great, I marked this topic as solved.