Changing dynamically created button's background in WPF

こ雲淡風輕ζ 提交于 2020-01-14 03:16:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!