首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不能同时使用ItemTemplate和ItemContainerStyle吗?

不能同时使用ItemTemplate和ItemContainerStyle吗?
EN

Stack Overflow用户
提问于 2015-03-11 13:07:26
回答 1查看 3.7K关注 0票数 5

我正在尝试将ItemTemplate和ItemContainerStyle应用于ItemsControl:-

代码语言:javascript
复制
<ItemsControl ItemsSource="{Binding LogEntries}"
              ItemTemplate="{StaticResource itemTemplate}"
              ItemContainerStyle="{StaticResource itemContainer}" />

然而,ItemContainerStyle似乎被忽略了(但是如果我删除了ItemTemplate,它就会起作用)。

项目模板相当复杂,并在许多不同的视图中使用。在一个特定的视图中,我需要更改列表项的间距和背景颜色,因此我也试图应用ItemContainerStyle,它如下所示:-

代码语言:javascript
复制
<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实际上只是项目内容的“包装器”,而不管项目的内容是否被模板化?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-11 14:13:36

ItemContainerStyle不是任何东西的‘包装’.这是一个Style。您可以同时设置item容器的StyleItemTemplate属性,但是您的问题是因为您试图在Style中设置ContentPresenterContentTemplate属性,并且这是用ItemTemplate的值覆盖的。(请参阅评论部分中的@克莱门斯链接)。

解决这一问题的一种方法是使用ListBox将其数据项封装在ListBoxItem中,并为Template属性而不是ContentTemplate提供一个值。(当然,您可以添加一个Style来删除它的边框,使它看起来像一个ItemsControl)。在这种情况下,ItemContainerStyle将影响ListBoxItem。然而,你必须理解其中的区别。

ItemContainerStyle将影响ListBoxItem,而ItemTemplate则用于定义内部的数据对象。因此,在Border中定义ItemContainerStyle并定义数据在ItemTemplate中的外观是合适的。试试这个:

代码语言:javascript
复制
<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>
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28987424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档