屏幕处于横向模式时的扩展布局显示半黑屏

问题描述

我有两个视图和两个内容页面,其中一个页面是垂直排列的,显示为设备处于纵向模式时的样子,

enter image description here

<StackLayout>
            <Grid>
                <Grid.RowDeFinitions>
                    <RowDeFinition Height="*"/>
                    <RowDeFinition Height="Auto"/>
                </Grid.RowDeFinitions>

                <views:scoresView Grid.Row="0"/>
                <views:CategoriesView Grid.Row="1"/>

            </Grid>
        </StackLayout>

其他内容页面为横向模式

<StackLayout>
        <Grid>
            <Grid.RowDeFinitions>
                <RowDeFinition Height="*"/>
            </Grid.RowDeFinitions>
            <Grid.ColumnDeFinitions>
                <ColumnDeFinition Width="*"/>
                <ColumnDeFinition Width="Auto"/>
            </Grid.ColumnDeFinitions>

            <views:scoresView Grid.Column="0"/>
            <views:CategoriesView Grid.Column="1"/>
        </Grid>
    </StackLayout>

我希望它看起来像这样

enter image description here

但是看起来像这样

enter image description here

这是我在轮换时打电话给另一个的方式

protected override void OnSizeAllocated(double width,double height)
        {
            base.OnSizeAllocated(width,height);
            if (width > height)
            {
                //device is landscape
                App.Current.MainPage = new CategoriesLands();
            }
            else
            {
                //device is portrait (or square)
            }
        }

...反之亦然

解决方法

您可以更改 StackLayout StackOrientation属性以实现效果。

<StackLayout x:Name="outerStack">       
     <views:ScoresView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>
     <views:CategoriesView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>
</StackLayout>

在后面的代码中:

private double width;
private double height;
protected override void OnSizeAllocated(double width,double height)
    {
        base.OnSizeAllocated(width,height);
        if (width != this.width || height != this.height)
        {
            this.width = width;
            this.height = height;
            if (width > height)
            {
                outerStack.Orientation = StackOrientation.Horizontal;
            }
            else
            {
                outerStack.Orientation = StackOrientation.Vertical;
            }
        }
    }

您可以参考的更多this