1

我有以下代码来动态创建按钮并将其添加到面板:

StackPanel topPanel=...;
Button button=new Button();

button.Content="New Button "+topPanel.Children.Count;      

// Set button background to a red/yellow linear gradient
// Create a default background brush
var bgBrush=new LinearGradientBrush(new GradientStopCollection(
   new GradientStop[] {new GradientStop(Color.FromRgb(255,255,200),0.5),
                       new GradientStop(Color.FromRgb(255,200,200),0.5)}));
// Create a more intense mouse over background brush
var bgMouseOverBrush=new LinearGradientBrush(new GradientStopCollection(
   new GradientStop[] {new GradientStop(Color.FromRgb(255,255,100),0.5),
                       new GradientStop(Color.FromRgb(255,100,100),0.5)}));

// Set the button's background
button.Background=bgBrush;
// Dynamically, add the button to the panel
topPanel.Children.Add(button);

问题是当我将鼠标光标移到按钮上时,它会恢复到以前的浅蓝色背景。现在,我已经读到我需要的是鼠标悬停按钮触发器,但我不知道如何仅针对这个按钮以编程方式执行此操作。基本上,我希望它的背景bgMouseOverBrush在鼠标光标在它上面时改变,然后bgBrush在它不在时改变。

4

1 回答 1

2

尝试这个:

    // In the constructor or any approp place
    button.MouseEnter += new MouseEventHandler(b_MouseEnter);
    button.MouseLeave += new MouseEventHandler(b_MouseLeave);

    void b_MouseLeave(object sender, MouseEventArgs e)
    {
        button.Background=bgBrush;
    }

    void b_MouseEnter(object sender, MouseEventArgs e)
    {
        button.Background = bgMouseOverBrush;
    }

希望有帮助。

编辑

鼠标输入 鼠标移到

鼠标移出 鼠标移出

于 2010-12-12T19:47:10.537 回答