【问题标题】:Not all ListBoxItem are created equal并非所有 ListBoxItem 都是平等的
【发布时间】:2010-09-04 18:03:44
【问题描述】:

在下面的示例中,DataTemplate 仅应用于第一个和第二个列表项,第三个和第四个被完全忽略。

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}"></Button>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <sys:String>One</sys:String>
    <sys:String>Two</sys:String>
    <ListBoxItem>Three</ListBoxItem>
    <ListBoxItem>Four</ListBoxItem>
</ListBox>

我的问题是为什么?

如果我查看输出窗口,我会看到以下错误:“ItemTemplate 和 ItemTemplateSelector 已被 ItemsControl 容器类型的项目忽略;类型='ListBoxItem'。

所以我明白了为什么我的模板没有被应用,但是当我在我的列表项上明确使用 ListBoxItems 对象时,为什么 WPF 对我很不利?我的意思是,WPF 在 ListBoxItems 对象上隐式托管 ALL 项,那么为什么 WPF 不能感谢我做了一些它应该做的工作而不是抛出错误呢? :)

谢谢。

【问题讨论】:

    标签: wpf listbox listboxitem


    【解决方案1】:

    这听起来更像是一个警告而不是错误 - 只是向您解释为什么您声明的 ItemTemplateListBoxItems 不能一起工作。

    编辑

    针对您的评论,请考虑以下事项:

        <ListBox>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.Items>
                <System:String>One</System:String>
                <System:String>Two</System:String>
                <ListBoxItem Background="Red">Three</ListBoxItem>
                <ListBoxItem>
                    <ListBoxItem.Template>
                        <ControlTemplate>
                            <Button Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}" 
                                    Background="Blue"
                                    Foreground="White"
                                    />
                        </ControlTemplate>
                    </ListBoxItem.Template>
                    <ListBoxItem.Content>
                        Four
                    </ListBoxItem.Content>
                </ListBoxItem>
            </ListBox.Items>
        </ListBox>
    

    ItemTemplate 视为定义显示项目类型的方式。对于字符串项目“One”和“Two”,ItemTemplate 定义了如何显示它,将结果包装在 ListBoxItem 中。

    但是,如果一个项目已经ListBoxItem

    1. 这不是ItemTemplate 必须处理的项目,因为ItemTemplateDataTemplate,并且
    2. ListBoxItem 可以定义自己的属性、样式和模板。

    因此,如果您明确创建 ListBoxItems,我认为 WPF 最好尊重自定义该项目样式的能力,而不是使用 ItemTemplate 覆盖它。

    这就是使用ItemTemplates 的美妙之处——您可以使用它们、混合、匹配和破坏它们,通常不必真正担心ListBoxItem。我唯一一次不得不直接处理ListBoxItem 是在我为它创建样式时——明确地声明一个作为项目可能充其量是极少数情况。

    【讨论】:

    • 我同意这更像是一个警告而不是一个错误,但我仍然很想了解为什么显式使用 ListBoxItem 会产生我的 DataTemplate 在幕后被忽略的副作用,WPF无论如何,将 ListBoxItems 添加到我的条目中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多