parentForm Reference如何为null?
我有一个应用程序,我在表单上添加了一个usercontrol。 当我在userControl构造函数中检查this.parentForm
,它给出了一个空引用
我的userControl代码就像
public UserControl1() { InitializeComponent(); if (this.ParentForm != null)//ParentReference is null { MessageBox.Show("Hi");//Does Not get Called } }
在创建控件时,它还没有被添加到表单中 – 所以当然父表单将为null。
即使你通常把它写成:
// Where form might be "this" form.Controls.Add(new UserControl1());
你应该把它想象成:
UserControl1 tmp = new UserControl1(); form.Controls.Add(tmp);
现在你的构造函数正在第一行执行,但第一次提到form
是在第二行……那么控件如何才能看到它呢?
您可能应该处理ParentChanged
事件,然后采取适当的措施。 (如果您不使用Windows窗体,请道歉 – 我确信其他UI框架具有相同的function;如果您可以说明您在问题中使用的内容,那么下次会很有用。)
为什么你添加这条线实际上没有必要,删除这一行
if (this.ParentForm != null)//ParentReference is null public UserControl1() { InitializeComponent(); MessageBox.Show("Hi");//Does Not get Called }