Marcin Bator Marcin Bator - 5 months ago 105
C# Question

WPF change button hover style programmatically

I want to create a custom style for buttons in my WPF application. I want to be able to change their

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)

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.



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

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

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.


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">
          To="90"  />
<EventTrigger RoutedEvent="Mouse.MouseLeave">
          Storyboard.TargetProperty="MaxHeight"  />

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


For your problem regarding button hover events see here