I am trying to add datatemplatate on listbox which contain some sample data, but their seems to be no effect on listboxitem of my dataTemplate, following is the code used-
<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>
The background of listboxitem is not turning to red, I know i can achieve similar thing using itemcontainerstyle but want to know why datatemplate is not getting applied here,
Well if you turn your Binding Error info on, then you'll see
System.Windows.Data Error: 26 : ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type; Type='ListBoxItem'
If you had your ListBox Bind it's ItemSource to a collection even say a List<string> MyStrings
such as
<ListBox ItemTemplate="{StaticResource test1}"
ItemsSource="{Binding MyStrings}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
and the DataTemplate
<DataTemplate x:Key="test1">
<TextBlock Background="Red"
Text="{Binding .}" />
</DataTemplate>
then you'll see your DataTemplate applied fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With