C# .Owner 属性和 ShowDialog(IWin32Window owner) 之间的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/395186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between .Owner property and ShowDialog(IWin32Window owner)?
提问by Preets
I presume a winform's owner can be set explicitly via the .Ownerproperty OR by passing the owner in the overloaded method ShowDialog(IWin32Window owner)
我认为可以通过.Owner属性或通过在重载方法ShowDialog(IWin32Window owner) 中传递所有者来显式设置 winform 的所有者
I am unable to understand why these methods exhibit different behavior when working with MDI forms.
我无法理解为什么这些方法在使用MDI 表单时表现出不同的行为。
I have created an MDIParent and an MDIChild.
我创建了一个 MDIParent 和一个 MDIChild。
I also have a simple winform MyDialogBox that displays its owner on load.
我还有一个简单的 winform MyDialogBox,它在加载时显示其所有者。
MessageBox.Show("Dialog's owner is " + this.Owner.Name);
Method A - In the load of MDIChild I have the following code, which causes the MyDialogBox's owner to be set to MDIChild
方法 A - 在 MDIChild 的负载中,我有以下代码,这会导致 MyDialogBox 的所有者设置为MDIChild
MyDialogBox box = new MyDialogBox();
box.Owner = this; // Set owner as MDIChild
box.ShowDialog();
Method B - Alternatively, in the load method of MDIChild I have the following code, which causes the MyDialogBox's owner to be set to MDIParent
方法 B - 或者,在 MDIChild 的加载方法中,我有以下代码,这会导致将 MyDialogBox 的所有者设置为MDIParent
MyDialogBox box = new MyDialogBox();
box.ShowDialog(this); // Pass MyMDIChild as owner
I also read the following here
我还在这里阅读了以下内容
Only the MDI parent form can own another form, be it a MDI child, a modal dialog or a form where the parent was set as the Owner param.
只有 MDI 父窗体可以拥有另一个窗体,可以是 MDI 子窗体、模态对话框或父窗体被设置为所有者参数的窗体。
If so Method A should not work at all, isn't it ?
如果是这样,方法 A 根本不应该起作用,不是吗?
What am I missing? Why doesn't method B set the owner to MDIChild ?
我错过了什么?为什么方法 B 不将所有者设置为 MDIChild ?
回答by SaguiItay
Looking at the differences of these 2 options using Reflector, it seems that they have a slightly different implementation:
box.Owner = this
just assign the provided value of this to the internal owner field.
However, when calling ShowDialog(IWin32Window)
, the implementation performs the following call, prior to assigning the value:
使用 Reflector 查看这 2 个选项的差异,似乎它们的实现略有不同:
box.Owner = this
只需将 this 提供的值分配给内部所有者字段。但是,在调用 时ShowDialog(IWin32Window)
,实现会在分配值之前执行以下调用:
owner = ((Control) owner).TopLevelControlInternal;
This might result in assignment of the MDIParent.
这可能会导致 MDIParent 的分配。
(Note: I'm far from being an expert regarding MDI, so I might be wrong here).
(注意:我远不是 MDI 方面的专家,所以我在这里可能是错的)。