如何让按钮做同样的事情? [英] How do I make buttons do the same thing?

查看:36
本文介绍了如何让按钮做同样的事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始编程,我想使用 WinForms 制作多个按钮,您可以单击这些按钮从白色变为浅绿色,再变为白色.我已经为一个按钮完成了此操作:

I just started programming, and I want to use WinForms to make multiple buttons that you can click on to change from white to lime-green and back to white. I have done this for one button:

private void button1_Click(object sender, EventArgs e)
    {
        if (button1.BackColor != Color.Lime)
        {
            button1.BackColor = Color.Lime;
        }
        else
        {
            button1.BackColor = Color.White;
        }
    }

现在我可以为所有按钮复制和粘贴它,但我知道这是低效的;如果我使用 winforms 在 button2 上引用 button1,它只会改变 button1 的颜色(显然).

Now I could copy and paste that for all of the buttons, but I know that is inefficient; and if I use winforms to reference button1 on button2, it will just change the color of button1 (obviously).

那么,我是否需要使用辅助方法、新类或其他东西?那会是什么样子?

So, do I need to use a helper method, new class, or something else? What would that look like?

推荐答案

有几种方法.一个可能是创建一个不同按钮调用的通用函数:

There are a couple of approaches. One might be to create a common function which the different buttons call:

private void button1_Click(object sender, EventArgs e)
{
    ChangeColor(button1);
}

private void ChangeColor(Button button)
{
    if (button.BackColor != Color.Lime)
        button.BackColor = Color.Lime;
    else
        button.BackColor = Color.White;
}

然后每个按钮处理程序都可以使用相同的函数调用.

Then each button handler can use that same function call.

或者,如果所有这些按钮总是做完全相同的事情,那么您可以对所有这些按钮使用一个单击处理函数.在这种情况下,您需要做的是确定哪个按钮调用了处理程序(而您当前直接引用了 button1),以便您知道要更改哪个按钮.传递给处理函数的 sender 对象实际上是对调用处理函数的表单元素的引用.你需要做的就是投射它:

Or, if all of these buttons will always ever do exactly the same thing, then you can use one click handler function for all of them. In this case what you'd need to do is determine which button invoked the handler (whereas you're currently referencing button1 directly) so that you know which one to change. The sender object passed into the handler function is actually a reference to the form element which invoked the handler. All you need to do is cast it:

private void button_Click(object sender, EventArgs e)
{
    var button = (Button)sender;
    if (button.BackColor != Color.Lime)
        button.BackColor = Color.Lime;
    else
        button.BackColor = Color.White;
}

因此,处理程序首先获取对调用它的按钮的引用,然后在该按钮上运行逻辑.还要注意我是如何使处理程序函数的名称更通用的.现在您将转到表单设计器并将 button_Click 设置为所有应该调用它的按钮的点击处理程序.

So first the handler grabs a reference to the button which invoked it, then runs the logic on that button. Note also how I made the name of the handler function slightly more generic. Now you'd go to the form designer and set button_Click as the click handler for all of the buttons which should invoke this.

这篇关于如何让按钮做同样的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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