Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms relative layout - get a stack layout centred inside

I have a Xamarin forms application where I use a relative layout to get some elements positioned very specifically. I want to have a stack layout centred right in the middle of the relative layout. I use this code:

_relativeLayout.Children.Add (
        _stackLayout, 
        Constraint.RelativeToParent(p => (p.Width / 2) - (_stackLayout.Width / 2) ),
        Constraint.RelativeToParent(p => (p.Height/ 2) - (_stackLayout.Height / 2) )

    );

When the form loads, I do not get the right result. The stack layout is way off to one side. However, if I rotate the screen one way and then back again, it looks perfect. So I gather that when the layout is rendered, the height and width of the stack layout have not yet been fully calculated, but on rotation these values are known so it renders properly.

How can I get the stack layout perfectly centred on initial form load?

like image 892
Whatever Man Avatar asked Aug 24 '14 02:08

Whatever Man


1 Answers

You can use the request values. Check if the Width/Height is -1 in which case it has not been initialized yet and you should use the request value. If it has been initialized then use it.

        this._relativeLayout.Children.Add(
            this._stackLayout, 
            Constraint.RelativeToParent(p => (p.Width / 2) - 
                ((this._stackLayout.Width == -1 ? this._stackLayout.WidthRequest : this._stackLayout.Width) / 2)),
            Constraint.RelativeToParent(p => (p.Height / 2) - 
                ((this._stackLayout.Height == -1 ? this._stackLayout.HeightRequest : this._stackLayout.Height) / 2))
        );
like image 134
SKall Avatar answered Sep 27 '22 22:09

SKall