简体   繁体   中英

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?

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))
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM