Xamarin.Forms 动态布局取决于屏幕方向或大小

Neu*_*uxz 5 c# xaml xamarin xamarin.forms

Xamarin.Forms 是否已经包含根据屏幕方向或大小对其内容进行排序的控件/布局?

我想要的是:如果屏幕有足够的空间,两个水平排列的堆栈布局。当屏幕发生变化,导致屏幕没有足够的水平空间时,两个stacklayouts 应该垂直排列。

我不想在后面的代码中做到这一点。

我寻找一个只使用 xaml 的解决方案。

Die*_*uza 6

我想你不能只使用 XAML 来实现这一点。当然,您将需要一些 c# 代码。Xamarin.Forms 上的 XAML 被设计为响应式,你经常以相对模式(而不是绝对模式)定义视图属性。

您可以在本主题中看到您想要的行为示例,其中我们可以看到屏幕根据设备方向更改 StackLayout 的方向(您可以将其用作编写自己的布局组件的指南)

纵向模式下的屏幕: 纵向模式下的屏幕

横向模式下的屏幕: 横向模式下的屏幕

这是通过以下 XAML 完成的:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ResponsiveLayout.StackLayoutPageXaml"
Title="Stack Photo Editor - XAML">
    <ContentPage.Content>
        <StackLayout Spacing="10" Padding="5" Orientation="Vertical"
        x:Name="outerStack"> <!-- can change orientation to make responsive -->
            <ScrollView>
                <StackLayout Spacing="5" HorizontalOptions="FillAndExpand"
                    WidthRequest="1000">
                    <StackLayout Orientation="Horizontal">
                        <Label Text="Name: " WidthRequest="75"
                            HorizontalOptions="Start" />
                        <Entry Text="deer.jpg"
                            HorizontalOptions="FillAndExpand" />
                    </StackLayout>
                    <StackLayout Orientation="Horizontal">
                        <Label Text="Date: " WidthRequest="75"
                            HorizontalOptions="Start" />
                        <Entry Text="07/05/2015"
                            HorizontalOptions="FillAndExpand" />
                    </StackLayout>
                    <StackLayout Orientation="Horizontal">
                        <Label Text="Tags:" WidthRequest="75"
                            HorizontalOptions="Start" />
                        <Entry Text="deer, tiger"
                            HorizontalOptions="FillAndExpand" />
                    </StackLayout>
                    <StackLayout Orientation="Horizontal">
                        <Button Text="Save" HorizontalOptions="FillAndExpand" />
                    </StackLayout>
                </StackLayout>
            </ScrollView>
            <Image  Source="deer.jpg" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)

一些 C# 用于根据设备的方向更改 externalStack 的方向:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望它能帮助你。