问题
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.
回答1:
Try this:
// 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;
}
Hope that helps.
EDIT
Mouse Enter
Mouse Out
来源:https://stackoverflow.com/questions/4423471/changing-dynamically-created-buttons-background-in-wpf