1

在下面的示例中,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 对象上的所有项目,那么为什么 WPF 不能感谢我做了一些它应该做的工作而不是抛出错误呢?:)

谢谢你。

4

1 回答 1

2

It sounds more like a warning than error -- just filling you in on why your declared ItemTemplate and ListBoxItems aren't going to work together.

edit

In response to your comment, consider the following:

    <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>

Think of the ItemTemplate as defining a way to display the item type. For items "One" and "Two", which are strings, the ItemTemplate defines how to display that and wraps the result in a ListBoxItem.

If, however, an item is already a ListBoxItem

  1. This is not an item that the ItemTemplate can necessarily deal with because an ItemTemplate is a DataTemplate, and
  2. The ListBoxItem can define its own properties, style, and template.

So, if you are explicitly creating ListBoxItems, I think it is better that WPF respect the ability to customize the styling of that item, rather than overriding it all with the ItemTemplate.

That's the beauty of using ItemTemplates -- you can use them, mix, match, and mangle them, usually without really having to worry about ListBoxItem. The only time I've ever had to deal with ListBoxItem directly is when I create a style for it -- declaring one as an item explicitly is probably a rare case at best.

于 2010-09-04T18:12:45.297 回答