When applying style for a ListBoxItem, today I come across a weird problem. I have trigger for both Mouse over and Selected. On selected, the item should goLightBlue and Gray on mouse hover. But when user clicks an item, it gets selected. But still the color remains Gray. But when user leaves the mouse, it turns out LightBlue.

On Mouse hover
On Mouse hover
On Selected
On Selected
On Selected and Mouse Over
On Selected and Mouse Over (Our real problem)

When I look into ListBoxItem Style, I could see that Mouse Over trigger added last, whereas Selected trigger came first. WPF will take the last trigger as high priority. Since we are changing the same property, the trigger which resolved last will set the property. And that is the reason the background looks gray. When I changed the style, looks like below, everything started working fine.


<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid>
<Rectangle Fill="{TemplateBinding Background}" />
<ContentPresenter Margin="10" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter Property="Background"
Value="Gray" />
</Trigger>
<Trigger Property="IsSelected"
Value="True">
<Setter Property="Background"
Value="LightBlue" />
</Trigger>
</Style.Triggers>
</Style>