wpf - 在 ItemsControl 中的每个项目周围包裹一些东西

标签 wpf datatemplate itemscontrol itemtemplate

假设我有一组不同类的对象。每个类在资源文件中都有其 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/

相关文章:

wpf - 基于枚举为数据模板选择用户控件

WPF : Dispatcher processing has been suspended, 但消息仍在处理中

没有 XAML 的 WPF

c# - WPF : Can BinaryFormatter serialize FlowDocument instance?

windows-phone-7 - WP7 - map - 在运行时编辑图钉模板的属性

wpf - 如何让 WPF 窗口扩展以适应动态变化的 ItemsControl 的内容?

c# - 我怎样才能找出是什么阻止了对象的垃圾收集?

c# - 当 SelectedItem 是 ContentControl 时,为什么此 ComboBox 会忽略 DataTemplate?

wpf - 如何在绑定(bind)的动态集合中的每个项目之间插入一个 GridSplitter 行

wpf - 将 Itemscontrol 绑定(bind)到 ObservableCollection : extra generated item