You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整MAUI Grid行高以适配多行文本的Label

解决MAUI Grid行高无法适配多行文本的问题

针对你遇到的Grid行高不随多行Label/RadioButton文本自动扩展的问题,可通过以下关键调整解决:

核心修改点

  • 将Grid行高设置为Auto:原代码中RowDefinition Height="*"会让行高按比例平分Grid可用空间,而非根据内容自适应。改为Auto后,行高会完全由单元格内的内容高度决定。
  • 强制Label文本换行:给Label添加LineBreakMode="WordWrap",确保长文本在小屏设备上正确换行,避免被截断或压缩。
  • 优化RadioButton布局对齐:给RadioButton设置VerticalOptions="Center",保证控件在自适应行高内垂直居中,同时让其Content文本正常换行显示。

修改后的完整代码

<ScrollView>
    <VerticalStackLayout>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="3*"/>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <Label x:Name="c1r1" 
                   Grid.Column="0" 
                   Grid.Row="0" 
                   Text="Some information that will span multiple rows. I'd like the row height to adjust accordingly." 
                   VerticalTextAlignment="Center"
                   LineBreakMode="WordWrap"/>
            <RadioButton x:Name="c2r1" 
                         Grid.Column="1" 
                         Grid.Row="0" 
                         Content="OK"
                         VerticalOptions="Center"/>
            <RadioButton x:Name="c3r1" 
                         Grid.Column="2" 
                         Grid.Row="0" 
                         Content="Not OK at all"
                         VerticalOptions="Center"/>

            <Label x:Name="c1r2" 
                   Grid.Column="0" 
                   Grid.Row="1" 
                   Text="Short text" 
                   VerticalTextAlignment="Center"/>
            <RadioButton x:Name="c2r2" 
                         Grid.Column="1" 
                         Grid.Row="1" 
                         Content="OK"
                         VerticalOptions="Center"/>
            <RadioButton x:Name="c3r2" 
                         Grid.Column="2" 
                         Grid.Row="1" 
                         Content="NOK"
                         VerticalOptions="Center"/>
        </Grid>
    </VerticalStackLayout>
</ScrollView>

动态添加字段的适配提示

如果是从XML动态生成输入字段,在创建RowDefinition时需确保将Height属性设置为GridLength.Auto,而非比例值或固定值,这样每一行都会根据自身内容自动调整高度。

内容的提问来源于stack exchange,提问作者Mats Claesgård

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:05:30