views:

249

answers:

1

I need to change the DataTemplate of my ListBox, based on the ListBox items count. I have come up with the following XAML:

<Window.Resources>
  <DataTemplate x:Key="DefaultTemplate">
    <StackPanel Orientation="Horizontal">
   <TextBlock Text="{Binding Path=Text}"/>
   <TextBlock Text="default template" />
    </StackPanel>
  </DataTemplate>
  <DataTemplate x:Key="OtherTemplate">
    <StackPanel Orientation="Horizontal">
   <TextBlock Text="{Binding Path=Text}"/>
   <TextBlock Text="other template" />
    </StackPanel>
  </DataTemplate>      
</Window.Resources>
<ListBox Name="listBox1" ItemsSource="{Binding Path=Items}">
  <ListBox.Style>
    <Style TargetType="{x:Type ListBox}">
      <Setter Property="ItemTemplate" Value="{StaticResource DefaultTemplate}" />
        <Style.Triggers>
          <DataTrigger Binding="{Binding Path=Items.Count}" Value="1">
             <Setter Property="ItemTemplate" Value="{StaticResource OtherTemplate}"/>
          </DataTrigger>
        </Style.Triggers>
     </Style>
  </ListBox.Style>     
</ListBox>

With the above XAML, once I added two or more items to the bound list, the data template changed as expected (from other to default). However, if I remove the first item in the list with more than two items, the entire listbox just becomes empty (I verified that the bound list is non-empty). Removing the second item in a two items list works fine though (i.e. template changed from default to other).

Any ideas why this is happening? Or perhaps I went about the wrong way to solve this problem?

A: 

you could use data triggers, or you could use a DataTemplateSelector Here is an article that shows the basics. and here is the MSDN on applying it to the items control (also, a listbox)

Muad'Dib