parentForm参考如何为空? [英] how parentForm Reference is null?

查看:533
本文介绍了parentForm参考如何为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我所添加的窗体上的用户控件的应用程序。
当我检查 this.parentForm 在该用户构造它给出了一个空引用



我的用户代码就像

 公开的UserControl1()
{
的InitializeComponent();
如果(this.ParentForm!= NULL)// ParentReference为null
{
MessageBox.Show(你好); //不会被调用
}
}


解决方案

在创建中的控制,它赢得。'吨已被添加到一个表单,但 - 所以当然父窗体将是空的。



即使你通常写为:

  //其中形式可能是这个
form.Controls.Add(新的UserControl1());

您应该认为它是:



 的UserControl1 TMP =新的UserControl1(); 
form.Controls.Add(TMP);

现在你的构造是在第一个的行执行,但第一格式是在第二的行...怎么可能控制有任何知名度?



您或许应该被处理 ParentChanged 事件,而是和采取适当的行动,那么。 (道歉,如果你不使用Windows窗体 - 我敢肯定有其他的UI框架等效;下一次将是有益的,如果你能说出您使用的是什么的问题)


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

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.

Even if you'd normally write it as:

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

You should think of it as:

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

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?

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参考如何为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆