5

I want to add a hover effect for a WPF-Control.

For this, I created a Style-Trigger that changes the Background-Brush of the control if IsMouseOver is true. This works fine, however if I open a ContextMenu from the control, IsMouseOver becomes false and the hover effect stops until the ContextMenu is closed.

I also tried a combination of MouseEnter and MouseLeave, but with this, there is the same behaviour. If the context menu` is opened, MouseLeave will be fired.

I understand why I can not do it like this, but I don't see a nice way to solve my requirement. Has anyone did already something like this?

HCL
  • 36,053
  • 27
  • 163
  • 213

1 Answers1

4

The issue can be resolved by the creation of a second trigger, that checks if the attached ContextMenu is opened:

<Trigger Property="IsMouseOver" Value="True">
     <Setter Property="Background" Value="{StaticResource Hover_Brush}"/>                                            
</Trigger>
<DataTrigger Binding="{Binding ContextMenu.IsOpen,RelativeSource={RelativeSource Mode=Self}}" Value="True">
     <Setter Property="Background" Value="{StaticResource Hover_Brush}"/>
</DataTrigger>

Caveat
The above XAML works fine, but has one issue: If the style is used for more than one item and the controls ContextMenu is shared, the hover effect will be activated on all items if the context menu is opened for a control.
Therefore, the context menu must not be shared. If it is defined in a resource, use the x:Shared="false" property to disable sharing. If it is directly defined under the control, this problem does not occur.

HCL
  • 36,053
  • 27
  • 163
  • 213