ListBox不使用其ItemTemplate

时间:2014-03-16 15:30:21

标签: wpf xaml listbox datatemplate

这个ListBox在世界上有什么问题?它将项目显示为纯字符串,而不是使用我提供的模板:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Ellipse Width="20" Height="20" Fill="LightBlue" />
                <TextBlock Text="{TemplateBinding Content}" Foreground="Red" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.Items>
        <ListBoxItem>html</ListBoxItem>
        <ListBoxItem>head</ListBoxItem>
        <ListBoxItem>body</ListBoxItem>
        <ListBoxItem>table</ListBoxItem>
        <ListBoxItem>tr</ListBoxItem>
        <ListBoxItem>td</ListBoxItem>
    </ListBox.Items>
</ListBox>

2 个答案:

答案 0 :(得分:3)

来自ItemTemplate MSDN page的备注部分:

  

在ItemsControl上设置ItemTemplate时,会生成UI   如下(以ListBox为例):

     

1.在内容生成期间,ItemsPanel发起对ItemContainerGenerator的请求,以便为每个数据项创建容器。   对于ListBox,容器是ListBoxItem。发电机回电   进入ItemsControl以准备容器。

     

2.准备工作的一部分涉及将ListBox的ItemTemplate复制为ListBoxItem的ContentTemplate。

     

3.与所有ContentControl类型类似,ListBoxItem的ControlTemplate包含ContentPresenter。应用模板时   它创建了一个ContentPresenter,其ContentTemplate绑定到   ListBoxItem的ContentTemplate。

     

4.最后,ContentPresenter将ContentTemplate应用于自身,并创建UI。

当您直接在XAML中创建ListBoxItem实例时,显然不会执行这些步骤。但是,绑定ItemSource属性并非绝对必要。您也可以直接设置如下项目:

<ListBox xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Ellipse Width="20" Height="20" Fill="LightBlue" />
                <TextBlock Text="{TemplateBinding Content}" Foreground="Red" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.Items>
        <sys:String>html</sys:String>
        <sys:String>head</sys:String>
        <sys:String>body</sys:String>
        <sys:String>table</sys:String>
        <sys:String>tr</sys:String>
        <sys:String>td</sys:String>
    </ListBox.Items>
</ListBox>

答案 1 :(得分:1)

public class MyViewModel
{
    public List<String> Items
    {
        get { return new List<String> { "html", "head", "body","table","tr","td" }; }
    }
}

//这可以在页面的Loaded事件中完成:

DataContext = new MyViewModel();

你的XAML

<ListBox Margin="20" ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
             <Ellipse Width="20" Height="20" Fill="LightBlue" />
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>