在WPF中更改动态创建的按钮背景
我有以下代码来动态创建并向面板添加按钮:
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);
问题是,当我将鼠标光标移到按钮上时,它会恢复到之前的浅蓝色背景。 现在,我已经读过我需要的是鼠标hover按钮触发器,但我不知道如何以编程方式单独为此按钮执行此操作。 基本上,我希望当鼠标光标在它bgBrush
时,它的背景变为bgBrush
当它不是时,我想要变成bgBrush
。
试试这个:
// 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; }
希望有所帮助。
编辑
鼠标输入
鼠标移出