繁体   English   中英

wpf c#更改鼠标悬停背景

[英]wpf c# Change mouse hover background

我目前正在学校做一个项目。

我在做扫雷。 外观如下:

扫雷

游戏网格由背景中带有图像的按钮组成。 除了鼠标悬停在按钮上之外,它的工作情况都非常完美。 背景变为浅蓝色:

鼠标问题

这是我用来定义按钮的代码:

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;
    }
}

到目前为止,我所看到的针对该问题的所有解决方案均以XAML编写,但对我的情况没有帮助。

如何以编程方式将其更改为当我将鼠标悬停在鼠标上时不会更改背景的状态?

为此,您必须修改按钮的控制模板:

xaml中将style定义为resources

<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>

然后在后面的代码中可以使用如下代码:

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;
   }
}

您将必须使用以下内容在鼠标悬停时更改Button的背景:

temp.MouseEnter += BtnFirstButton_MouseEnter;

private void temp_MouseEnter(object sender, MouseEventArgs e)
{
    if (btnFirstButton.IsMouseOver)
        btnFirstButton.Background = <color>;

    else
        btnFirstButton.Background = <color>;
}

您还可以定义一种Style并将其应用于Buttons这将避免此事件的注册。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM