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

Gug*_*uge 6 wpf datatemplate itemtemplate itemscontrol

假设我有一组不同类的对象.每个类在资源文件中都有UserControl DataTemplated.

现在我想使用ItemsControl来显示集合,但我希望每个项目周围都有一个Border或Expander.

我希望这样的东西能起作用:

<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>
Run Code Online (Sandbox Code Playgroud)

但是ContentPresenter似乎选择了ItemTemplate,因为我得到了堆栈溢出.

如何在ItemTemplate中获取每个Item的DataTemplate?

Jac*_*eja 13

通常,您可以考虑通过模板化项容器来完成此操作.问题是"泛型" ItemsControl使用ContentPresenter作为其项容器.因此,即使您尝试设置样式,ItemContainerStyle您也会发现无法提供模板,因为 ContentPresenter它不支持控件模板(它确实支持数据模板但在此处没有用).

要使用可模压容器,您必须ItemsControl像本示例中那样进行驱动.

替代方案可能只是使用ListBox控件.然后,您可以ListBoxItem通过样式设置模板来提供自定义模板.

你可以阅读更多关于集装箱在这里.

(使用你的permissen我正在为你的答案添加解决方案,Guge)

    <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>
Run Code Online (Sandbox Code Playgroud)