2

I am just getting into WPF. I have two event handlers:

private void Mouse_Enter(object sender, MouseEventArgs e)
{
    ((Button)sender).Background = Brushes.Red;
}
private void Mouse_Leave(object sender, MouseEventArgs e)
{
    ((Button)sender).Background = Brushes.Black;
}

When the mouse enters the button's area, nothing happens. However, when leaving the button's area, the button does go black. I have put a breakpoint inside Mouse_Enter and it is definitely executing the method, just doesn't change the background color.

How to fix it? Thanks!

Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • Does your button change color to the default "button hover" color when your mouse enters? – Fleury26 Nov 23 '17 at 20:55
  • @Fleury26 Yes, it does. – Gabriel Haddad Nov 23 '17 at 21:04
  • 2
    If it doesn't need to be in the c# code and can be in the XAML i suggest looking at [this answer](https://stackoverflow.com/questions/20073294/change-color-of-button-when-mouse-is-over) – Fleury26 Nov 23 '17 at 21:27
  • There is a lot more to re-styling a button than just overriding the background color. The default template can be found [here on msdn](https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/button-styles-and-templates) – Manfred Radlwimmer Nov 24 '17 at 08:24

1 Answers1

0

This is happening because there is a "built-in" trigger in the default button template that's causing the button to ignore your attempts to change it's background on a MouseEnter event, you will need to edit the template and disable the trigger first, follow these steps:

In the Visual Studio editor right click on your button and pick "Edit Template" then "Edit a Copy..." name your style whatever you want and look through the XAML for a trigger called "IsMouseOver" and delete the 2 lines below.

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsDefaulted" Value="true">
                            <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
    --- Delete this line    <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
    --- Delete this line    <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="true">
Dark Templar
  • 1,130
  • 8
  • 10
  • Thanks a lot, but I really want to do it using code-behind. Not for production purposes of course, but just for learning. Could you please explain how would I fix it without using XAML triggers? Thanks again! – Gabriel Haddad Nov 24 '17 at 10:05