问题描述
我有一个应用程序,我在表单上添加了一个用户控件.当我在 userControl 构造函数中检查 this.parentForm
时,它给出了一个空引用
I have an application in which i have added a usercontrol on the form.
When i check this.parentForm
in the userControl constructor it gives a null reference
我的 userControl 代码是这样的
My userControl Code is like
public UserControl1()
{
InitializeComponent();
if (this.ParentForm != null)//ParentReference is null
{
MessageBox.Show("Hi");//Does Not get Called
}
}
推荐答案
当控件被创建时,它还没有被添加到表单中——所以父表单当然是空的.
When the control is being created, it won't have been added to a form yet - so of course the parent form will be null.
即使您通常将其写为:
// Where form might be "this"
form.Controls.Add(new UserControl1());
你应该认为它是:
UserControl1 tmp = new UserControl1();
form.Controls.Add(tmp);
现在您的构造函数正在 first 行中执行,但 form
的第一次提及是在 second 行中......所以控件怎么能看到它?
Now your constructor is being executed in the first line, but the first mention of form
is in the second line... so how could the control have any visibility of it?
您可能应该处理 ParentChanged
事件,然后采取适当的行动.(抱歉,如果您没有使用 Windows 窗体 - 我确信其他 UI 框架也有类似的框架;如果您能在问题中说明您使用的内容,下次会很有用.)
You should probably be handling the ParentChanged
event instead, and taking appropriate action then. (Apologies if you're not using Windows Forms - I'm sure there's an equivalent for other UI frameworks; next time it would be useful if you could state what you're using in the question.)
这篇关于parentForm 引用如何为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!