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.
Wpf - how to correctly use MouseEnter, Click, and MouseLeave to change background of a ToggleButton?
-
08-07-2023 - |
Question
I have a weird issue with a set of ToggleButton
s. I am using them for a rating control that looks like the following:
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 ToggleButton
s to a light yellow like so:
The MouseLeave
event resets the Foreground
of all ToggleButton
s to what it used to be.
The Click
event is supposed to immediately set the Foreground
of the current and previous ToggleButton
s 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?
Solution