如何让ListBox ItemTemplate水平拉伸ListBox的全部宽度?

我想让ListItems的橙色背景延伸到ListBox的整个宽度。

目前它们只与FirstName + LastName一样宽。

我已经设置了每个元素:Horizo​​ntalAlignment =“Stretch”。

我希望ListboxItems的背景随着用户拉伸Listbox而展开,所以我不想放入绝对值。

我需要做什么,以便ListBoxItems的背景颜色填充ListBox的宽度?

<Window x:Class="TestListBoxSelectedItemStyle.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestListBoxSelectedItemStyle" Title="Window1" Height="300" Width="300"> <Window.Resources> <local:CustomerViewModel x:Key="TheDataProvider"/> <DataTemplate x:Key="CustomerItemTemplate"> <Border CornerRadius="5" Background="Orange" HorizontalAlignment="Stretch" Padding="5" Margin="3"> <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Width="Auto"> <TextBlock HorizontalAlignment="Stretch"> <TextBlock.Text> <MultiBinding StringFormat="{}{0} {1}"> <Binding Path="FirstName"/> <Binding Path="LastName"/> </MultiBinding> </TextBlock.Text> </TextBlock> </StackPanel> </Border> </DataTemplate> </Window.Resources> <Grid> <ListBox ItemsSource="{Binding Path=GetAllCustomers, Source={StaticResource TheDataProvider}}" ItemTemplate="{StaticResource CustomerItemTemplate}"/> </Grid> </Window> 

我确定这是重复的,但我找不到具有相同答案的问题。

HorizontalContentAlignment="Stretch"添加到您的ListBox。 这应该够了吧。 只需要小心自动完成,因为错误地获取HorizontalAlignment非常容易。

我在这里find了另一个解决scheme ,因为我遇到了两个post…

这是从Myles回答:

 <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> </Style> </ListBox.ItemContainerStyle> 

这对我有效。

如果您的项目比ListBox ,这里的其他答案将无济于事: ItemTemplate的项目仍然比ListBox宽。

这个修补程序对我来说是禁用了水平滚动条,显然,它也告诉容器所有这些项目保持与列表框一样宽。

因此,获取与列表框一样宽的ListBox项目的组合修复,无论它们是否较小,需要拉伸,还是较宽并且需要包装,如下所示:

 <ListBox HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled"> 

( 为滚动条想法信用 )

由于边框仅用于视觉效果,因此可以将其放入ListBoxItem的ControlTemplate中,并修改其中的属性。 在ItemTemplate中,只能放置StackPanel和TextBlock。 通过这种方式,代码也保持清洁,因为控件的外观将通过ControlTemplate进行控制,所显示的数据将通过DataTemplate进行控制。

对我来说,修复是在ScrollViewe r的ItemsPresenter上设置属性HorizontalAlignment="Stretch"

希望这可以帮助别人…

 <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBox"> <ScrollViewer x:Name="ScrollViewer" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" Padding="{TemplateBinding Padding}" HorizontalAlignment="Stretch"> <ItemsPresenter Height="252" HorizontalAlignment="Stretch"/> </ScrollViewer> </ControlTemplate> </Setter.Value> </Setter> 

我也有同样的问题,作为一个快速的解决方法,我用混合来确定多less填充被添加。 在我的情况下是12,所以我用一个负边缘来摆脱它。 现在一切都可以正确居中了