假设我有一组不同类的对象。每个类在资源文件中都有其 UserControl DataTemplated。
现在我想使用 ItemsControl 来显示集合,但我想要每个项目周围的边框或扩展器。
我希望这样的事情可以工作:
<ItemsControl ItemsSource="{Binding MyObjects}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="3">
<ContentPresenter/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但是 ContentPresenter 似乎选择了 ItemTemplate,因为我得到了堆栈溢出。
如何在 ItemTemplate 中获取每个 Item 的 DataTemplate?
最佳答案
通常,您可能会考虑通过模板化项目容器来执行此操作。问题是“通用”ItemsControl
使用 ContentPresenter
作为其项目容器。因此,即使您尝试使用 ItemContainerStyle
设置样式你会发现你不能提供模板,因为 ContentPresenter
不支持控制模板(它确实支持数据模板,但这里没有用)。
要使用可模板化的容器,您必须从 ItemsControl
派生。像这样 example .
另一种方法可能只是使用 ListBox
代替控制。然后您可以通过设置 ListBoxItem
来提供自定义模板。通过样式的模板。
您可以阅读有关容器的更多信息 here .
(经过您的许可,我将解决方案添加到您的答案中,古格)
<ListBox ItemsSource="{Binding MyObjects}" Grid.Column="1">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border BorderBrush="Black" BorderThickness="3">
<ContentPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
关于wpf - 在 ItemsControl 中的每个项目周围包裹一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4003709/