Change Style of ListBoxItem when we use ItemTemplate in ListBox.

We will see how can we change background and foreground of any ListBoxItem on MouseOver or on Selection, and for ListBoxItem, ItemTemplate is being used.

Consider a ListBox in XAML, in which, ListBoxItem contains multiple Label via ItemTemplate. Now you want the background color and the text color of the Labels to be changed on Mouse Over or on Selection of the Item. To achieve this we can use following style:

Scenario to Achieve:

To change the Foreground of the text we will use following style on the Labels:

<Style TargetType="{x:Type Label}" x:Key="listBoxLabel">
  <Setter Property="Foreground" Value="Black"></Setter>
      <!--Triggers for the IsSelected Property to check selection status-->
      <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsSelected}" Value="True">
            <Setter Property="Foreground" Value="White"></Setter>
      <!--Triggers for the IsMouseOver Property to check focus status-->
      <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsMouseOver}" Value="True">
          <Setter Property="Foreground" Value="Red"></Setter>

To change the Background of the Item we will write following style for the ListBox: