我有一个应用程序,其中我在表单上添加了用户控件。
当我检查时this.parentForm
在 userControl 构造函数中,它给出了一个空引用
我的用户控制代码就像
public UserControl1()
{
InitializeComponent();
if (this.ParentForm != null)//ParentReference is null
{
MessageBox.Show("Hi");//Does Not get Called
}
}
创建控件时,它还没有被添加到表单中 - 因此父表单当然将为空。
即使您通常将其写为:
// Where form might be "this"
form.Controls.Add(new UserControl1());
您应该将其视为:
UserControl1 tmp = new UserControl1();
form.Controls.Add(tmp);
现在你的构造函数正在执行first线,但第一次提到form
在里面second线...那么控件怎么能看到它呢?
你可能应该处理ParentChanged事件,然后采取适当的行动。 (如果您不使用 Windows 窗体,我深表歉意 - 我确信其他 UI 框架也有类似的框架;下次如果您能说明您在问题中使用的内容,将会很有用。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)