C# – WPF change button hover style programmatically

buttoncwpf

I want to create a custom style for buttons in my WPF application. I want to be able to change their Backgroound and BorderThickness properties when mouse is over them.

Some of the buttons are created dynamically in c# so I don't think that xaml solution will be enough.

I tried achieving my goal using Triggers and Setters in c#, but I couldn't get it to work, hover color always stayed light blue.

Here is how I'm creating buttons:

Button but = new Button()
{
Height = 40,
Background = new SolidColorBrush(Colors.Gray),
Content = new Label() { 
    FontSize = 13, 
    FontWeight = FontWeights.Medium, 
    Foreground = new SolidColorBrush(Colors.White)
    }
}
stackPanel.Children.Add(but)

I know this is not the best way to create controls and I could probably be better off using MVVM, but I can't change the whole application so I'm just looking for a c# solution.

Thanks!

EDIT:

I added a style to App.xaml file. It looks like this (UpperMenuModeButton is my control based on regular button):

<Application.Resources>
    <Style TargetType="UpperMenuModeButton" x:Key="UpperMenuModeButton" >
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="Red"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Application.Resources>

I am setting the style while creating the button like this:

this.Style = (Style) Resources["UpperMenuModeButton"];

I am still getting regular light blue background on hover.

Best Answer

You can create a general style like this:

<Style TargetType="Button">
  <Setter Property="HorizontalAlignment" Value="Center" />
  <Setter Property="FontFamily" Value="Comic Sans MS"/>
  <Setter Property="FontSize" Value="14"/>
<EventTrigger RoutedEvent="Mouse.MouseEnter">
  <EventTrigger.Actions>
    <BeginStoryboard>
      <Storyboard>
        <DoubleAnimation
          Duration="0:0:0.2"
          Storyboard.TargetProperty="MaxHeight"
          To="90"  />
      </Storyboard>
    </BeginStoryboard>
  </EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="Mouse.MouseLeave">
  <EventTrigger.Actions>
    <BeginStoryboard>
      <Storyboard>
        <DoubleAnimation
          Duration="0:0:1"
          Storyboard.TargetProperty="MaxHeight"  />
      </Storyboard>
    </BeginStoryboard>
  </EventTrigger.Actions>
</EventTrigger>
</Style>

Put this code in the scope of your buttons (in it's page or grid or container) and it'll work automatically. For more info see here

Edit

For your problem regarding button hover events see here

Related Topic