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

.NET MAUI Grid无法垂直扩展的问题求助

Grid仅占用约50%垂直空间的解决方案

问题根源

  1. 外层VerticalStackLayout未设置VerticalOptions="FillAndExpand",导致它仅包裹内容高度,内部Grid无法获取完整垂直空间
  2. 布局索引错误:StackLayout指定Grid.Column="2",但Grid仅定义了2列(索引0、1),越界索引会导致布局异常
  3. RowSpan设置超出Grid行范围:Frame和StackLayout设置Grid.RowSpan="2",但Grid仅3行,Grid.Row="2"加上RowSpan会超出布局边界

修复后的XAML代码

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="BXMT.MainPage"
             Shell.NavBarIsVisible="False">

    <!-- 给外层VerticalStackLayout添加FillAndExpand,让它填满页面垂直空间 -->
    <VerticalStackLayout Spacing="25" VerticalOptions="FillAndExpand">
        <Grid VerticalOptions="FillAndExpand">
            <Grid.RowDefinitions>
                <!-- 调整行比例,让标题行占比更小,内容行占比更大 -->
                <RowDefinition Height="0.5*"/>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="2*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            
            <!-- 标题放在第1行(索引0),横跨两列 -->
            <Label Grid.ColumnSpan="2" Grid.Row="0" 
                Text="Title Label" HorizontalTextAlignment="Center"
                VerticalTextAlignment="Center" Padding="0,20,0,20"
                HorizontalOptions="FillAndExpand" VerticalOptions="Center" />
            
            <!-- Frame放在第2行(索引1),第1列(索引0),占满该行 -->
            <Frame Grid.Row="1" Grid.Column="0"
                BorderColor="LightGray" BackgroundColor="Transparent"
                VerticalOptions="FillAndExpand" Margin="20">
            </Frame>
            
            <!-- 按钮容器放在第2行(索引1),第2列(索引1),修正列索引错误 -->
            <StackLayout Grid.Row="1" Grid.Column="1" 
                Padding="30" Spacing="20"
                Margin="40" VerticalOptions="Center">
                <Button Text="Button 1" />
                <Button Text="Button 2" />
            </StackLayout>
        </Grid>
    </VerticalStackLayout>

</ContentPage>

关键修改说明

  • 给外层VerticalStackLayout设置VerticalOptions="FillAndExpand",确保它填满整个页面的垂直空间,内部Grid才能继承完整空间
  • 修正StackLayout的Grid.Column为1,匹配Grid的列定义
  • 调整Grid行比例,让标题、Frame/按钮区域的高度分配更合理,同时移除超出范围的RowSpan设置,避免布局异常
  • 调整标题的VerticalOptions为Center,让标题在对应行内垂直居中,提升视觉效果

内容的提问来源于stack exchange,提问作者Planeptunia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:15:24