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

WPF中如何为ListBox列表项末尾添加铺满全宽的蓝色水平线

WPF ListBox列表项蓝色横线铺满全宽解决方案

核心原因

ListBox的子项容器ListBoxItem默认HorizontalContentAlignment属性为Left,导致内部DataTemplate的内容仅能适配自身内容宽度,即便内部元素设置HorizontalAlignment="Stretch"也无法占满整个列表项宽度。

修复方案

在ListBox标签内添加ItemContainerStyle配置,强制列表项容器的内容区域拉伸占满全宽即可,修改后的完整代码如下:

<Grid>
    <ListBox Name="MyListBoxAddData" Margin="20" BorderThickness="0">
        <!-- 新增列表项容器样式 -->
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            </Style>
        </ListBox.ItemContainerStyle>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <Label Content="{Binding Id}"/>
                    <Label Content="{Binding Path=Questions,Mode=TwoWay}"/>
                    <RadioButton Content="{Binding Path=Option1,Mode=TwoWay}" Margin="10 5"/>
                    <RadioButton Content="{Binding Path=Option2,Mode=TwoWay}" Margin="10 5"/>
                    <RadioButton Content="{Binding Path=Option3,Mode=TwoWay}" Margin="10 5"/>
                    <RadioButton Content="{Binding Path=Option4,Mode=TwoWay}" Margin="10 5"/>
                    <TextBlock Text="{Binding Answer}" />
                    <Separator HorizontalContentAlignment="Stretch"/>
                    <Rectangle HorizontalAlignment="Stretch" Fill="Blue" Height="4" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

如果不需要默认的Separator分隔线,可以直接删除对应标签,仅保留蓝色Rectangle即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:57:03