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

WPF中如何让XAML Grid根据内容调整宽高

WPF Grid行无法向下拉伸的解决方法

你的问题出在内部Grid的RowDefinition没有设置正确的高度模式,默认空标签等价于Height="Auto",行只会根据内部控件高度自适应,不会填充Grid的剩余垂直空间。要让行能拉伸,需把需要占满剩余空间的行设置为Height="*",其他行保持Auto即可。

修改后的完整代码如下:

<Window x:Class="Diploma.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Diploma"
        Title="MainWindow" Height="450" Width="800"
        Background="LightCyan"
        >
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition Width="3*"/>
            <ColumnDefinition Width="200"/>
        </Grid.ColumnDefinitions>
        <Grid Grid.Column="0" Grid.Row="0" Margin="10 10 10 10">
            <Grid.RowDefinitions>
                <!-- Label行:自适应内容高度 -->
                <RowDefinition Height="Auto"/>
                <!-- 搜索栏行:自适应内容高度 -->
                <RowDefinition Height="Auto"/>
                <!-- ListBox行:填充剩余垂直空间 -->
                <RowDefinition Height="*"/>
                <!-- 按钮行:自适应内容高度 -->
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Label Grid.Column="0" Grid.Row="0">
                Записи
            </Label>

            <Grid Grid.Column="0" Grid.Row="1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>

                <TextBox Grid.Column="0" Grid.Row="0" Height="20"></TextBox>
                
                <Button Grid.Column="1" Grid.Row="0" Height="20" Width="60">
                    Поиск
                </Button>
            </Grid>
            
            <ListBox Grid.Column="0" Grid.Row="2"></ListBox>
            <Button Grid.Column="0" Grid.Row="3" MaxHeight="20">
                Загрузить
            </Button>

        </Grid>
        <!--<GridSplitter Grid.Column="1" ShowsPreview="False" Width="3"
            HorizontalAlignment="Center" VerticalAlignment="Stretch"/>-->
    </Grid>
</Window>

关键调整说明:

  • 将第三行(ListBox所在行)的RowDefinition设置为Height="*",该行会占据Grid中所有未被其他行占用的垂直空间,实现拉伸效果。
  • 其他行设置为Height="Auto",确保它们只占用自身内容所需高度,不浪费空间。

调整后,窗口大小改变时,ListBox所在行会自动拉伸填充可用空间,满足可调整大小表单的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:43:45