Wpf - how to correctly use MouseEnter, Click, and MouseLeave to change background of a ToggleButton?

StackOverflow https://stackoverflow.com/questions/23252032

  •  08-07-2023
  •  | 
  •  

Question

I have a weird issue with a set of ToggleButtons. I am using them for a rating control that looks like the following:

rating control

Each ToggleButton listens to the following events:

rating_button.MouseEnter += new MouseEventHandler(rating_button_mouse_entered);
rating_button.Click += new RoutedEventHandler(rating_button_clicked);
rating_button.MouseLeave += new MouseEventHandler(rating_button_mouse_left);

When the mouse enters over a ToggleButton, the MouseEnter event sets the Foreground of the current and previous ToggleButtons to a light yellow like so:

hover and click

The MouseLeave event resets the Foreground of all ToggleButtons to what it used to be.

The Click event is supposed to immediately set the Foreground of the current and previous ToggleButtons to gold (so the 4 stars in the second image should have the same color as the first image). Now here comes the problem - setting the Foreground in this event handler actually does nothing! The backgrounds are not set until MouseLeave fires.

If I do not set the MouseEnter and MouseLeave event handlers, the Foreground changes immediately in the Click handler, which is the desired behavior. However, the hover functionality obviously will not work.

What can I do to fix this issue?

Was it helpful?

Solution

On your event handlers you have to set the Handled property to true if you don't want the event to bubble up from MouseEnter -> Click. So that it won't change the Foreground immediately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top