在 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);
问题是,当我将鼠标光标移到按钮上时,它会恢复到之前的浅蓝色背景。现在,我已经读到我需要的是一个鼠标悬停按钮触发器,但我不知道如何仅针对该按钮以编程方式执行此操作。基本上,我希望当鼠标光标位于其上方时,其背景更改为 bgMouseOverBrush
,而当鼠标光标不在其上方时,则返回至 bgBrush
。
I have the following code to dynamically create and add a button to a panel:
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);
The problem is that when I move the mouse cursor over the button, it reverts to its previous light blue background. Now, I have read that what I need is a mouseover button trigger, but I have no idea how to do this programatically just for this button, alone. Basically, I want its background to change to bgMouseOverBrush
when the mouse cursor is over it and back to bgBrush
when it is not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
希望有帮助。
编辑
鼠标输入
鼠标移出
Try this:
Hope that helps.
EDIT
Mouse Enter
Mouse Out