在WPF中更改动态创建的按钮背景

时间:2010-12-12 19:15:40

标签: c# c#-4.0 wpf-controls wpf-4.0

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

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

1 个答案:

答案 0 :(得分: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;
    }

希望有所帮助。

修改

鼠标输入 MouseOver

鼠标输出 Mouse Out