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

如何让WPF DataGrid列自适应填充剩余全部空间

解决DataGrid右侧空白无法自适应填充的问题

以下几个调整可以直接解决你的问题:

  1. 禁用DataGrid横向滚动条
    给DataGrid添加**HorizontalScrollBarVisibility="Disabled"**,这会强制DataGrid的列填满可用宽度,避免因允许横向滚动而保留右侧空白。

  2. 让DataGrid填满父容器宽度
    给DataGrid绑定Width到父级ContentPresenter的实际宽度,确保它不会自行收缩:
    Width="{Binding RelativeSource={RelativeSource AncestorType=ContentPresenter}, Path=ActualWidth}"

  3. 保留列宽度的正确设置
    维持最右侧列的Width="*"配置,同时确认第一列固定宽度Width="150"符合你的需求。

修改后的完整DataGrid代码片段:

<DataGrid Grid.Row="1"
          AutoGenerateColumns="False"
          HorizontalAlignment="Stretch"
          HorizontalContentAlignment="Stretch"
          VerticalAlignment="Top"
          HorizontalScrollBarVisibility="Disabled"
          Width="{Binding RelativeSource={RelativeSource AncestorType=ContentPresenter}, Path=ActualWidth}"
          ItemsSource="{Binding PackParameters}">
    <DataGrid.Resources>
        <DataTemplate DataType="{x:Type local:TextStateParameter}">
            <TextBox Text="{Binding Value}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn
            Width="150"
            Binding="{Binding Name}" />
        <DataGridTemplateColumn
            Width="*">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ContentPresenter Content="{Binding}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

原因说明

  • 默认情况下DataGrid允许横向滚动,即使列总宽度小于容器宽度,也会保留空白区域而非自动拉伸列。禁用横向滚动后,它会强制列填满所有可用空间。
  • 绑定Width到父ContentPresenter的ActualWidth,能确保DataGrid完全占据ItemsControl分配的宽度,避免因自身布局逻辑导致收缩。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:25:28