问题描述
我刚开始编程,我想使用的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引用BUTTON1上按钮2,它只会改变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?
我AP preciate任何帮助,任何人都可以给。请记住,我是初学者所以请大声说话,慢慢地。)
I appreciate any help that anyone can give. Remember, I am a beginner so please speak loudly and slowly :).
感谢。
推荐答案
有几个方法。其中一个可能是创建一个共同的功能,不同的按钮调用:
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.
或如果所有这些按钮会一直真能完全一样的东西,那么你可以使用点击处理函数为所有的人。在这种情况下,你会需要做的是(按钮1
直接而你目前引用)确定哪个按钮调用的处理程序,让你知道改哪一个。传递到处理函数的发件人
对象实际上是到调用的处理表单元素的引用。所有你需要做的是将它转换:
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.
这篇关于如何让我的按钮做同样的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!