代码之家  ›  专栏  ›  技术社区  ›  Guge

在ItemsControl中的每个项周围包装一些内容

  •  4
  • Guge  · 技术社区  · 15 年前

    假设我有一个不同类的对象集合。每个类在资源文件中都有其UserControl数据模板。

    现在我想使用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中获取每个项的数据模板?

    1 回复  |  直到 15 年前
        1
  •  13
  •   Guge    15 年前

    通常,您可以考虑通过模板化项目容器来实现这一点。问题是“通用” ItemsControl 使用 ContentPresenter 作为它的物品容器。所以即使你试着用 ItemContainerStyle 您将发现无法提供模板,因为 任命者 不支持控件模板化(它确实支持数据模板化,但此处不使用)。

    项目控件 就像这个 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>
    
        2
  •  1
  •   N. Kudryavtsev    7 年前

    我只需要做以下事情:

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Black" BorderThickness="3">
                <ContentControl Content={Binding} />
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    

    DataTemplate 标记是源集合中的项,我们可以使用 ContentControl 显示此项。 {Binding} 数据模板 ItemsControl.ItemTemplate .