Add similar behavior to a group of WinForms contro

2019-03-03 16:32发布

I have a form with 6 buttons. These buttons serve to increase/decrease tha value of the respective textbox. Now I'm trying to "animate" the buttons. I want to get another effect on the button when the mouse is over him.

My form

To do that, I have two diferent images in Resources and I am doing this code:

private void btnHoursDown_MouseHover(object sender, EventArgs e) {
    btnHoursDown.Image = Game_Helper.Properties.Resources.DownHover;
}

private void btnHoursDown_MouseLeave(object sender, EventArgs e) {
    btnHoursDown.Image = Game_Helper.Properties.Resources.Down;
}

This works fine. My question is: it wouldn't be wise to create a class (ButtonBehaviour.cs) and put this code in that class?

So I would have something like this:

ButtonBehaviour buttonBehaviour = new ButtonBehaviour();
private void btnHoursDown_MouseHover(object sender, EventArgs e) {
    buttonBehaviour.buttonDownHover();
}

private void btnHoursDown_MouseLeave(object sender, EventArgs e) {
    buttonBehaviour.buttonDownLeave();
}

And the class should be:

public class ButtonBehaviour {
    public void buttonDownHover() {
       // code
    }

    public void buttonDownLeave() {
       // code
    }
}

How can I create this Class Behaviour and make the buttons adapt this Behaviour?

1条回答
对你真心纯属浪费
2楼-- · 2019-03-03 17:26

if one effect should be applied for all buttons, try to add the same event handlers to them

private void btn_MouseHover(object sender, EventArgs e)
{
    (sender as Button).Image = Game_Helper.Properties.Resources.DownHover;
}

private void btn_MouseLeave(object sender, EventArgs e)
{
    (sender as Button).Image = Game_Helper.Properties.Resources.Down;
}

button which raised event is available via sender variable

this way you avoid code duplication for every button. creating a ButtonBehaviour or CustomButton is probably an over-engineering unless you need them in many forms

查看更多
登录 后发表回答