Change WPF DataTemplate for ListBox item if selected

The easiest way to do this is to supply a template for the “ItemContainerStyle” and NOT the “ItemTemplate” property. In the code below I create 2 data templates: one for the “unselected” and one for the “selected” states. I then create a template for the “ItemContainerStyle” which is the actual “ListBoxItem” that contains the item. I set the default “ContentTemplate” to the “Unselected” state, and then supply a trigger that swaps out the template when the “IsSelected” property is true. (Note: I am setting the “ItemsSource” property in the code behind to a list of strings for simplicity)

<Window.Resources>

<DataTemplate x:Key="ItemTemplate">
    <TextBlock Text="{Binding}" Foreground="Red" />
</DataTemplate>

<DataTemplate x:Key="SelectedTemplate">
    <TextBlock Text="{Binding}" Foreground="White" />
</DataTemplate>

<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
    <Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
        </Trigger>
    </Style.Triggers>
</Style>

</Window.Resources>
<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource ContainerStyle}" />

Leave a Comment