parentForm 引用如何为空?

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

问题描述

我有一个应用程序,我在表单上添加了一个用户控件.当我在 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 引用如何为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)