[英]wpf c# Change mouse hover background
I'm currently working on a project at school. 我目前正在学校做一个项目。
I'm making Minesweeper. 我在做扫雷。 Here's how it looks:
外观如下:
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:
背景变为浅蓝色:
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. 到目前为止,我所看到的针对该问题的所有解决方案均以XAML编写,但对我的情况没有帮助。
how to programmaticaly change it to a state that it wont change the background when i houver the mouse? 如何以编程方式将其更改为当我将鼠标悬停在鼠标上时不会更改背景的状态?
To achieve this you have to modify button's control template: 为此,您必须修改按钮的控制模板:
define your style
as a resources
in 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>
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;
}
}
You will have to use the following to change the background of the Button
on mouse over: 您将必须使用以下内容在鼠标悬停时更改
Button
的背景:
temp.MouseEnter += BtnFirstButton_MouseEnter;
private void temp_MouseEnter(object sender, MouseEventArgs e)
{
if (btnFirstButton.IsMouseOver)
btnFirstButton.Background = <color>;
else
btnFirstButton.Background = <color>;
}
You can also define a Style
and apply it to the Buttons
this will avoid this registering of this event. 您还可以定义一种
Style
并将其应用于Buttons
这将避免此事件的注册。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.