表单内的静态成员

时间:2014-05-05 07:44:05

标签: c# windows-forms-designer

在我的WindowsForms项目中,如果我在表单中有一个静态实例,那么当我第一次打开我的表单时,它就可以了。但如果我关闭它并再次打开,表单将为空。为什么会这样?

public partial class Computer : Form
    {
        static Indicators indicators = new Code.Indicators();
    }

P.S。我将其设为静态,因为我希望在表单关闭后保存它的值。

修改1:打开表单

private void button3_Click(object sender, EventArgs e)
        {
            Computer computer = new Computer();
            computer.ShowDialog();
        }

编辑2:计算机表格

namespace WF
{
    public partial class Computer : Form
    {
        static Code.Indicators indicators = new Code.Indicators();

        public Computer()
        {
            if (indicators.isComputerAlreadyRunning == false)
            {
                InitializeComponent();
                pictureBox1.Image = Properties.Resources.Computer1;
                indicators.isComputerAlreadyRunning = true;
            }
        }

        // My not successful try to save the value of the variable
        public Code.Indicators ShowForm()
        {
            return new Code.Indicators(indicators.isComputerAlreadyRunning);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

我不认为静态成员在Windows窗体生命周期中运行良好。

我建议你让Indicators成为表单的正常实例成员。为了保持表单生命周期内的状态,您可以从表单中复制您的状态,并在打开表单时将其复制回表单。

// Keep this in the proper place 
var indicators = new Code.Indicators();

...

// Copy back and forth for the life time of the form
using (var form = new Computer())
{
    form.Indicators.AddRange(indicators);
    form.Close += (s, e) => 
        {
            indicators.Clear();
            indicators.AddRange(form.Indicators);
        }
}

...

答案 1 :(得分:2)

根据Computer类中的构造函数,第一次创建表单时indicators.isComputerAlreadyRunning设置为true。

因此,当第二次创建Computer时,if条件将失败,并且将跳过整个if块。这意味着您的InitializeComponent();无法运行,因此表单中的任何内容都不会显示。

InitializeComponent();置于if子句之外以使其正常工作。

相关问题