.net WPF-listbox itemtemplate中未应用Datatemplate
我试图在包含一些示例数据的listbox上添加dataTemplate,但它们似乎对我的dataTemplate的listboxitem没有影响,下面是使用的代码-.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>
<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>