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