Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Datatemplate Not getting applied in listbox itemtemplate

Tags:

.net

wpf

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,

like image 910
ankush Avatar asked Nov 24 '25 01:11

ankush


1 Answers

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.

like image 185
Viv Avatar answered Nov 26 '25 14:11

Viv