Dolev Dolev - 1 year ago 117
C# Question

wpf c# Change mouse hover background

I'm currently working on a project at school.

I'm making Minesweeper. Here's how it looks:

Minesweeper

The game grid is made of buttons with image in the background.
It's working perfectly, except when the mouse hovers over a button; the background changes to light blue:

Mouse Problem

Here's the code I've been using to define the buttons:

for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Button temp = new Button();
temp.Background = situationImages[0];
temp.Height = 16;
temp.Width = 16;
temp.Click += window.button_Click;
temp.MouseRightButtonUp += window.button_Right_Click;
gameGrid.Children.Add(temp);
Grid.SetRow(temp, j);
Grid.SetColumn(temp, i);
MainWindow.buttons[i, j] = temp;
}
}


All solutions that I've seen so far for this problem is written in XAML but it doesn't help my case.

how to programmaticaly change it to a state that it wont change the background when i houver the mouse?

Answer Source

To achieve this you have to modify button's control template:

define your style as a resources in xaml

<Style x:Key="btnStyle" TargetType="{x:Type Button}">    
        <Setter Property="Background" Value="Gray"/>        
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="Gray"/>
            </Trigger>
        </Style.Triggers>
 </Style>

and then in code behind you can use it something like this:

for (int i = 0; i < row; i++)
{
  for (int j = 0; j < col; j++)
  {
    Button temp = new Button();
    temp.Background = situationImages[0];
    temp.Height = 16;
    temp.Width = 16;
    temp.Style = this.FindResource("btnStyle") as Style; // Apply your style here
    temp.Click += window.button_Click;
    temp.MouseRightButtonUp += window.button_Right_Click;
    gameGrid.Children.Add(temp);
    Grid.SetRow(temp, j);
    Grid.SetColumn(temp, i);
    MainWindow.buttons[i, j] = temp;
   }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download