我想让ListItems以其橙色背景扩展到Listbox的整个宽度。 ide
目前,它们的大小仅与名字+姓氏同样。 spa
我已经设置了全部能够设置的元素:HorizontalAlignment =“ Stretch”。 code
我但愿ListboxItems的背景在用户拉伸Listbox时扩展,因此我不想输入绝对值。 orm
我该怎么作才能使ListBoxItems的背景颜色填充ListBox的宽度? xml
<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>
若是您的项目比ListBox
宽 ,则此处的其余答案将无济于事: ItemTemplate
的项目仍然比ListBox
宽。 get
对我有用的解决方法是禁用水平滚动条,显然,这也告诉容器全部这些项目的宽度仅与列表框同样宽。 it
所以,得到与列表框同样宽的ListBox项的组合修补程序以下:它们较小且须要拉伸,仍是较宽且须要包装,以下所示: io
<ListBox HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
( 感谢滚动条的想法 ) ast
因为边框仅用于视觉外观,所以能够将其放入ListBoxItem的ControlTemplate中,而后在其中修改属性。 在ItemTemplate中,您只能放置StackPanel和TextBlock。 这样,代码也保持干净,由于控件的外观将经过ControlTemplate进行控制,而要显示的数据将经过DataTemplate进行控制。 容器
自从我遇到这两个职位以来,我在这里找到了另外一个解决方案 ...
这是从迈尔斯的答案:
<ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> </Style> </ListBox.ItemContainerStyle>
这对我有用。
对我来讲,解决方法是在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>
我也遇到了一样的问题,做为一种快速的解决方法,我使用blend来肯定要添加多少填充。 在个人例子中是12,因此我用负的余量来消除它。 如今一切均可以正确居中了