Xamarin.Forms - 在后面的代码中更改控件的大小

Xamarin.Forms - change size of control in code behind

我想在 Xamarin.Forms 中使用控件隐藏代码中的某些事件更改控件的大小。

特别是,我想在设备方向发生变化时更改 StackLayout 的大小。

目前,我是这样做的(但它不起作用):

private void SettingsPage_OnSizeChanged(object sender, EventArgs e)
{
    var isPortrait = UIHelpers.IsPortrait(this);
    if (isPortrait)
        RemoteServerSL.WidthRequest = RemoteServerSL.ParentView.Width;
    else
    {
        RemoteServerSL.WidthRequest = RemoteServerSL.ParentView.Width/2;
    }

    this.UpdateChildrenLayout();
    this.ForceLayout();
    RemoteServerSL.ForceLayout();

}

目的是在横向模式下将我的 StackLayout 的宽度更改为 parentWidth。

我该如何处理?

BTW.I目前正在 Android。

您应该使用 OnSizeAllocated 方法覆盖来检测方向变化;

double previousWidth;
double previousHeight;

    protected override void OnSizeAllocated(double width, double height)
    {
        base.OnSizeAllocated(width, height);

        if (previousWidth != width || previousHeight != height)
        {
            previousWidth = width;
            previousHeight = height;

            if (width > height)
            {
                // landscape mode
            }
            else
            {
                // portrait mode
            }   
        }
    }