我正在尝试将 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 实际上只是项目内容的“包装器”,无论项目的内容是否模板化?
The ItemContainerStyle
is not任何东西的“包装”......它是一个Style
. You can设置两个Style
物品容器的and the ItemTemplate
属性,但你的问题是因为你试图设置ContentTemplate
的财产ContentPresenter
在你的Style
这会被值覆盖ItemTemplate
。 (请参阅评论部分中的@Clemens 链接)。
解决这个问题的一种方法是使用ListBox
将其数据项包装在ListBoxItem
s 并提供一个值Template
属性而不是ContentTemplate
。 (当然你可以添加一个Style
删除它的边框,使其看起来像ItemsControl
)。在这种情况下,ItemContainerStyle
将影响ListBoxItem
反而。但是,您必须了解其中的区别。
The ItemContainerStyle
将影响ListBoxItem
,而ItemTemplate
用来定义里面的数据对象。因此,定义一个Border
in the 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)