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))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With