WPF - Datatemplate未在listbox itemtemplate中应用

ank*_*ush 3 .net wpf

我试图在列表框中添加包含一些示例数据的datatemplatate,但它们似乎对我的dataTemplate的listboxitem没有影响,以下是使用的代码 -

<Page
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.Resources>
            <DataTemplate x:Key="test1">
                <TextBlock Background="Red">
                </TextBlock>
            </DataTemplate>
        </Grid.Resources>
        <ListBox ItemTemplate="{StaticResource test1}">
            <ListBoxItem>A</ListBoxItem>
            <ListBoxItem>B</ListBoxItem>
            <ListBoxItem>C</ListBoxItem>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"  ></StackPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </Grid>
</Page>
Run Code Online (Sandbox Code Playgroud)

listboxitem的背景并没有变成红色,我知道我可以使用itemcontainerstyle实现类似的东西但是想知道为什么没有在这里应用datatemplate,

Viv*_*Viv 7

好吧,如果你打开你的绑定错误信息,那么你会看到

System.Windows.Data Error: 26 : ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type; Type='ListBoxItem'
Run Code Online (Sandbox Code Playgroud)

如果你有你的ListBoxBind,它ItemSource甚至可以说是一个集合List<string> MyStrings

<ListBox ItemTemplate="{StaticResource test1}"
          ItemsSource="{Binding MyStrings}">
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

DataTemplate

<DataTemplate x:Key="test1">
  <TextBlock Background="Red"
              Text="{Binding .}" />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

然后你会看到你DataTemplate应用的罚款.