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