Era*_*ray 2 c# refresh winforms
我是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();
*/
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,当用户单击YES或NO按钮之一时,应重新执行整个构造函数.标签应该是"你只需按下YES/NO按钮".
但是当我使用this.Refresh()时,当我按下按钮时没有任何事情发生.仍然标签是"请按下这些按钮之一:".
当我使用this.Invalidate()时,所有按钮都消失了,标签仍然是"请按下其中一个按钮:".
我该怎么办 ?
谢谢.
无效或刷新不会再次调用构造函数.在创建表单时,构造函数只调用一次,而无效则不会创建新表单.把改变东西的逻辑放在另一个方法中,然后从构造函数和事件处理程序中调用它 - 但请注意后代调用实例方法或从构造函数中访问变量并不是最好的方法 - 但是对于你在这里的目的是简单的解决方案.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1053 次 |
最近记录: |