我是 C# 的新手,我有一个小项目。我被困在某个地方了。我在这里解释了它(带有示例源代码):
我有一个表格申请。我要求用户从 2 个按钮中选择一个选项。有 2 个按钮(是和否)。我的代码是这样的:
public partial class Form1 : Form
{
public int choice=0;
public Form1()
{
if(choice == 0)
{
label.Text = "Please push one of these buttons :";
// And there are buttons below this label
}
else if(choice == 1)
{
label.Text = "You just pushed YES button";
}
else if(choice == 2)
{
label.Text = "You just pushed NO button";
}
}
private void buttonYes_Click(object sender, EventArgs e)
{
choice = 1;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
}
private void buttonNo_Click(object sender, EventArgs e)
{
choice = 2;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
}
}
如您所见,当用户单击"is"或“否”按钮之一时,应该重新执行整个构造函数。标签应该是“你刚刚按下是/否按钮”。
但是当我使用 this.Refresh() 时,当我点击按钮时没有任何反应。仍然标签是“请按这些按钮之一:”。
当我使用 this.Invalidate() 时,所有按钮都消失了,标签仍然是“请按这些按钮之一:”。
我该怎么办?
谢谢。
附言 我找到了 this question在问这个之前。但如您所见,接受的答案对我不起作用。
最佳答案
无效或刷新不会再次调用构造函数。创建表单时只调用一次构造函数,并且无效不会创建新表单。将更改内容的逻辑放在另一个方法中,并从构造函数和事件处理程序中调用它 - 但请注意后代调用实例方法或从构造函数访问变量并不是做这些事情的最好方法 - 但对于您在这里的目的是简单的解决方案。
public partial class Form1 : Form
{
public int choice=0;
public Form1()
{
UpdateForm();
}
private void UpdateForm(){
if(choice == 0)
{
label.Text = "Please push one of these buttons :";
// And there are buttons below this label
}
else if(choice == 1)
{
label.Text = "You just pushed YES button";
}
else if(choice == 2)
{
label.Text = "You just pushed NO button";
}
}
private void buttonYes_Click(object sender, EventArgs e)
{
choice = 1;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
UpdateForm();
}
private void buttonNo_Click(object sender, EventArgs e)
{
choice = 2;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
UpdateForm();
}
}
关于c# - 反复使用Form Constructor刷新标签文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820805/