我想知道为什么在ListBox中使用ListBoxItem?我发现当我在进行数据绑定时,你不需要ListBoxItem,在某些情况下我发现没有它会更好。
它是什么原因?它只适用于硬编码的东西吗?
答案 0 :(得分:0)
即使你不使用ListBoxItem
(并且你是对的,没有太多理由使用它来定义项目),ListBox
控件仍然使用它。也就是说,它使用它来包装列表中每个项目的数据模板。有一次你可能有机会在你的XAML代码中引用它,就是在设置项目容器样式时 - 使用ItemContainerStyle
完成:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
以上是一个常见示例,因为如果您希望ListBox中的项目水平伸展,则必须使用该方法。 (将项目DataTemplate设置为拉伸本身不起作用,因为默认情况下包含ListBoxItem是左对齐的。)
这是一个完整的例子。
<ListBox ItemsSource="{Binding Letters}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="Green">
<TextBlock Text="{Binding}" Foreground="White" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<!--
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
-->
</ListBox>
如下所示:
取消注释ItemContainerStyle
,它显示如下: