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
相关产品推荐
相关产品推荐

