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

使用ItemsControl时如何让子项填充全部剩余空间?

问题:ItemsControl中自定义DisplayLabel控件无法填充剩余空间的简便解决方法

我制作了一个用于展示参数的简单自定义控件DisplayLabel,并将多个该控件放入ItemsControl中。尝试让这些子项填充全部剩余空间,但VerticalContentAlignment未生效,使用UniformGrid包裹也无法实现。由于项目中这类控件数量较多,不想使用过多RowDefinition,求简便实现方法。

原代码如下:

<Grid Background="{StaticResource BackgroundLightBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition Height="auto" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>

    <!--  Title  -->
    <Grid Height="56">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="auto" />
        </Grid.ColumnDefinitions>

        <TextBlock
            Margin="20,15"
            VerticalAlignment="Center"
            FontSize="{StaticResource FontForTitle}"
            Text="{Binding Title}" />
        <Button
            Grid.Column="2"
            Width="{Binding ActualHeight, RelativeSource={RelativeSource self}}"
            Height="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType=StackPanel}}"
            Margin="7"
            Style="{StaticResource MenuButton}"
            Visibility="{Binding ButtonVisibility, Converter={local:BooleanToVisibilityConverter}}" />
    </Grid>

    <!--  Status Bars  -->
    <Border
        Grid.Row="1"
        Height="{Binding StatusBarsHeight}"
        Background="{Binding Status,Converter={local:LightGrayToGreenByBooleanConverter}}"
        />

    <!--  Parameter  -->
    <ItemsControl Grid.Row="2" ItemsSource="{Binding Items}" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <local:DisplayLabel />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

</Grid>

解决方案

核心修改:给ItemsControl指定UniformGrid作为ItemsPanel并绑定行数

直接修改ItemsControl的ItemsPanel,使用UniformGrid并将其Rows绑定到数据源的数量,同时确保DisplayLabel支持垂直拉伸:

<!--  Parameter  -->
<ItemsControl Grid.Row="2" ItemsSource="{Binding Items}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <!-- 绑定行数到Items的数量,让每个子项占一行且高度均分 -->
            <UniformGrid Rows="{Binding Items.Count, RelativeSource={RelativeSource AncestorType=ItemsControl}}" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <!-- 设置DisplayLabel垂直拉伸 -->
            <local:DisplayLabel VerticalAlignment="Stretch" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

额外注意事项

  • 确保DisplayLabel的根布局元素(比如内部的Grid/Border)的VerticalAlignment设为Stretch,且没有固定Height属性,这样才能跟随UniformGrid的行高拉伸。
  • 原Grid的第三行是Height="1*",已经提供了足够的剩余空间,无需修改父容器布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:42:11