parentForm Reference如何为null?

时间:2012-01-09 06:13:54

标签: c# c#-4.0 user-controls

我有一个应用程序,我在表单上添加了一个usercontrol。 当我在userControl构造函数中检查this.parentForm时,它会给出一个空引用

我的userControl代码就像

public UserControl1()
        {
            InitializeComponent();
            if (this.ParentForm != null)//ParentReference is null
            {
                MessageBox.Show("Hi");//Does Not get Called
            }
        }

2 个答案:

答案 0 :(得分:8)

当创建控件时,它还没有被添加到表单中 - 所以当然父表单将为null。

即使您通常将其写为:

// Where form might be "this"
form.Controls.Add(new UserControl1());

您应该将其视为:

UserControl1 tmp = new UserControl1();
form.Controls.Add(tmp);

现在你的构造函数正在第一个行中执行,但第一次提到form是在第二个行...所以怎么可能控制有任何可见性吗?

您可能应该处理ParentChanged事件,然后采取适当的措施。 (如果您不使用Windows窗体,请道歉 - 我确信其他UI框架的等效内容;如果您可以说明您在其中使用的内容,那么下次会很有用问题。)

答案 1 :(得分:0)

你添加了这行不需要什么,删除这一行

 if (this.ParentForm != null)//ParentReference is null

public UserControl1()
        {
            InitializeComponent();            
            MessageBox.Show("Hi");//Does Not get Called

        }