【发布时间】:2017-07-10 22:51:11
【问题描述】:
我正在学习 C#,并且已经完成了使用 Windows 窗体创建计算器的练习。现在我只添加了 9 个用于数字的按钮和 4 个用于临时操作的按钮(+、-、*、/)以及一个将数字作为字符串写入的标签。目前我正在这样做:
private void button1_Click(object sender, EventArgs e)
{
WriteInLabel(1);
}
private void button2_Click(object sender, EventArgs e)
{
WriteInLabel(2);
}
//etc.
//function to write the Text in label1
private void WriteInLabel(int i)
{
label1.Text += i.ToString();
}
记住 DRY 原则,这对我来说看起来像是一种糟糕的编写代码。 有没有办法更好地写这个?我想到了一个按钮数组/列表之类的东西。所以我可以这样做:
for(int i = 0; i < btnArr.Length; i++)
{
//Is this the correct syntax for appending an eventListener?
btnArr[i]Click += (sender, args) => WriteInLabel(i);
}
现在的问题是,我想在 Windows-forms-Designer-View 中编辑按钮属性。 这样自己写的代码能得到Buttons的Design-View吗?
Button btn1 = new Button();
或者是否可以从 Form1 自动创建一个按钮数组? 我试过这个(没用):
List<Button> btnList = new List<Button>();
foreach(Button btn in Form1)
{
btnList.Add(btn);
}
【问题讨论】:
-
什么方法没用?这将取决于按钮是如何制作的,是否将它们作为子元素添加到表单等?
-
好吧,我只是通过将按钮窗体从工具箱拖到 Form1 来添加它们。我在上一个代码 sn-p 中得到 Form1 下的红色波浪线,表示:Form1 是一种类型,在当前上下文中无效。
标签: c# arrays winforms button windows-forms-designer