我的问题是我有一个标签,我称之为“暂存器”。
然后我有11个按钮(数字0-9和。)。现在我的解决方案目前如下:
(注意:点尚未实现)
private void button0_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"0";
private void button1_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"1";
private void button2_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"2";
private void button3_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"3";
private void button4_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"4";
private void button5_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"5";
private void button6_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"6";
private void button7_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"7";
private void button8_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"8";
private void button9_Click(object sender, EventArgs e) => label_scratchpad.Text = label_scratchpad.Text + @"9";
有没有更好的方法来编码?
假设每个按钮都有相应的数字作为标题,您可以在设计时为所有按钮分配相同的处理程序
private void button_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
label_scratchpad.Text = label_scratchpad.Text + btn.Text;
}
对于Event绑定部分,在表单加载中将所有事件添加到按钮。
private void MyForm_Load(object sender, EventArgs e)
{
btn0.Click += digitClicked;
btn1.Click += digitClicked;
btn2.Click += digitClicked;
btn3.Click += digitClicked;
btn4.Click += digitClicked;
btn5.Click += digitClicked;
btn6.Click += digitClicked;
btn7.Click += digitClicked;
btn8.Click += digitClicked;
btn9.Click += digitClicked;
}
private void digitClicked(object sender, EventArgs e)
{
var btn = (Button)sender;
txtLogin.Text += btn.Text;
}
如果你不能使用btn.Text,我会使用按钮的Tag属性来敲击最后的字符串0,1 .....,9和点。
private void button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
label_scratchpad.Text = label_scratchpad.Text + (string)button.Tag;
}