向一组WinForms控件添加类似的行为 [英] Add similar behavior to a group of WinForms controls

查看:52
本文介绍了向一组WinForms控件添加类似的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有6个按钮的表格。这些按钮用于增加/减少相应文本框的值。现在,我尝试对按钮进行动画处理。当鼠标悬停在按钮上时,我想对按钮进行另一种效果。

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.

为此,我在Resources中有两个不同的图像,并且正在执行以下代码:

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;
}

这很好。我的问题是:创建一个类(ButtonBehaviour.cs)并将此代码放在该类中是不明智的?

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();
}

该类应为:

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?

推荐答案

如果所有按钮都应应用一种效果,尝试向其添加相同的事件处理程序

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;
}

按钮,通过发件人可以使用引发事件的按钮变量

这样,您可以避免每个按钮的代码重复。创建 ButtonBehaviour CustomButton 可能是一项过度工程,除非您需要多种形式的

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

这篇关于向一组WinForms控件添加类似的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆