简体   繁体   English

Xamarin形成相对布局 - 获得一个居中的堆栈布局

[英]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. 我有一个Xamarin表单应用程序,我使用相对布局来非常具体地定位一些元素。 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. 检查Width / Height是否为-1,在这种情况下它尚未初始化,您应该使用请求值。 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))
        );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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