我正在尝试将ItemTemplate和ItemContainerStyle应用于ItemsControl:-
<ItemsControl ItemsSource="{Binding LogEntries}"
ItemTemplate="{StaticResource itemTemplate}"
ItemContainerStyle="{StaticResource itemContainer}" />然而,ItemContainerStyle似乎被忽略了(但是如果我删除了ItemTemplate,它就会起作用)。
项目模板相当复杂,并在许多不同的视图中使用。在一个特定的视图中,我需要更改列表项的间距和背景颜色,因此我也试图应用ItemContainerStyle,它如下所示:-
<Style x:Key="itemContainer"
TargetType="ContentPresenter">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Border x:Name="itemBorder"
Margin="4,0,4,4"
Background="#666666">
<ContentPresenter Content="{Binding}" />
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>我有点惊讶你不能同时申请,除非我漏掉了什么?我认为ItemContainerStyle实际上只是项目内容的“包装器”,而不管项目的内容是否被模板化?
发布于 2015-03-11 14:13:36
ItemContainerStyle不是任何东西的‘包装’.这是一个Style。您可以同时设置item容器的Style和ItemTemplate属性,但是您的问题是因为您试图在Style中设置ContentPresenter的ContentTemplate属性,并且这是用ItemTemplate的值覆盖的。(请参阅评论部分中的@克莱门斯链接)。
解决这一问题的一种方法是使用ListBox将其数据项封装在ListBoxItem中,并为Template属性而不是ContentTemplate提供一个值。(当然,您可以添加一个Style来删除它的边框,使它看起来像一个ItemsControl)。在这种情况下,ItemContainerStyle将影响ListBoxItem。然而,你必须理解其中的区别。
ItemContainerStyle将影响ListBoxItem,而ItemTemplate则用于定义内部的数据对象。因此,在Border中定义ItemContainerStyle并定义数据在ItemTemplate中的外观是合适的。试试这个:
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Margin="4,0,4,4" Background="#666666">
<ContentPresenter Content="{Binding}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>https://stackoverflow.com/questions/28987424
复制相似问题