Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net WPF-listbox itemtemplate中未应用Datatemplate_.net_Wpf - Fatal编程技术网

.net WPF-listbox itemtemplate中未应用Datatemplate

.net WPF-listbox itemtemplate中未应用Datatemplate,.net,wpf,.net,Wpf,我试图在包含一些示例数据的listbox上添加dataTemplate,但它们似乎对我的dataTemplate的listboxitem没有影响,下面是使用的代码- <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid>

我试图在包含一些示例数据的listbox上添加dataTemplate,但它们似乎对我的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>

A.
B
C

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

如果打开绑定错误信息,您会看到

System.Windows.Data Error: 26 : ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type; Type='ListBoxItem'
如果您让您的
列表框
将其
ItemSource
绑定到一个集合,甚至可以说是一个
列表MyStrings

比如

<ListBox ItemTemplate="{StaticResource test1}"
          ItemsSource="{Binding MyStrings}">
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
</ListBox>
然后您将看到您的
DataTemplate
应用良好

<DataTemplate x:Key="test1">
  <TextBlock Background="Red"
              Text="{Binding .}" />
</DataTemplate>