为啥我的 Xamarin.Forms 控件在 StackLayout 中重叠?

Posted

技术标签:

【中文标题】为啥我的 Xamarin.Forms 控件在 StackLayout 中重叠?【英文标题】:Why are my Xamarin.Forms controls overlapping in my StackLayout?为什么我的 Xamarin.Forms 控件在 StackLayout 中重叠? 【发布时间】:2020-08-31 19:22:48 【问题描述】:

我正在尝试使用 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="DJB.Views.LoginPage"
             xmlns:local="clr-namespace:DJB.Controls">

    <ContentPage.Content>
        <StackLayout>
            <Image Source="djblogowithtext" Margin="30,30"></Image>
            <!-- UserName -->
            <Label Text="Username" HorizontalTextAlignment="Center" HeightRequest="15" Margin="1"/>
            <StackLayout BackgroundColor="LightGray" Padding="1" Margin="30,0" HeightRequest="20">
                <local:TextEntry BackgroundColor="White" VerticalOptions="FillAndExpand"/>
            </StackLayout>
            <!-- Password -->
            <Label Text="Password" HorizontalTextAlignment="Center" HeightRequest="15" Margin="1"/>
            <StackLayout BackgroundColor="LightGray" Padding="1" Margin="30,0" HeightRequest="20">
                <local:TextEntry BackgroundColor="White" VerticalOptions="FillAndExpand" />
            </StackLayout>

            <Button Text="Login" Margin="30" BackgroundColor="#f7ebeb" Clicked="Login_Clicked"> </Button>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

这是它在 android 上的样子:

我确信这很简单,但我是 Xamarin.Forms 的新手,所以不知道为什么会这样。

【问题讨论】:

【参考方案1】:

您正在为不足以容纳其内容的控件指定高度。要么根本不使用,让控件自行调整大小,要么使用对内容足够大的值。

<Label Text="Username" HorizontalTextAlignment="Center" HeightRequest="15" Margin="1"/>

具有默认字体的标签可能需要 30 或更高的高度,而不是 15

【讨论】:

谢谢@Jason。我摆脱了高度请求线,现在看起来很好。

以上是关于为啥我的 Xamarin.Forms 控件在 StackLayout 中重叠?的主要内容,如果未能解决你的问题,请参考以下文章

为啥在使用 Prism 在 Xamarin.Forms 中导航到 root 时,我的 NavigationPage 顶部会出现默认标题?

Xamarin Forms 命令在自定义控件中始终为空

蒙面的入口控件 Xamarin.forms

为啥活动指示器在 Xamarin.forms 中不起作用?

自定义控件的 Xamarin 数据绑定值计算为 Xamarin.Forms.Binding

为啥我的 Xamarin Forms iOS 应用程序在使用 Microsoft Azure 移动服务时崩溃