giovedì 11 agosto 2011

Choosing a DataTemplate based on properties or status of items

If you have a collection of the same type of data objects you could create a different DataTemplate for items that are of the same type but want to give it a completely different look based on a property or a status of the item itself.
Using the ItemTemplateSelector property of the ListBox could not be the right choice if the new DataTemplate should be triggered on a property change (e.g: change the DataTemplate when the item is selected)

I found out a solution here:
http://codingcontext.wordpress.com/2008/09/28/changing-the-data-template-for-the-currently-selected-item/

A easy solution could be create a new ItemContainerStyle for the ListBox. The ItemTemplate property must not be assigned.

<ListBox Width="400" Margin="10"
         ItemsSource="{Binding myList}"
         ItemContainerStyle="{StaticResource myListBoxItemStyle}"
         HorizontalContentAlignment="Stretch"/>

<Style x:Key="myListBoxItemStyle" TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource ListBoxItemStyle} >
  <Setter Property="ContentTemplate" Value="{StaticResource myNormalDataTemplate}"/>
    <Style.Triggers>
      <DataTrigger Binding="{Binding IsSpecial}" Value="True">
        <Setter Property="ContentTemplate" Value="{StaticResource mySpecialDataTemplate}"/>                                 
     </DataTrigger>   
  </Style.Triggers>
</Style>

You can download a sample here

Nessun commento:

Posta un commento