【问题标题】:How to ensure only one instance of a child form is created by a parent mdi form in VB.NET如何确保 VB.NET 中的父 mdi 表单仅创建子表单的一个实例
【发布时间】:2012-11-23 19:28:40
【问题描述】:
我在父表单上有一个按钮,可以创建新的子表单。
但是,我不希望为每个表单创建多个实例。我尝试在父 MDI 表单上放置一个公共布尔值:
Dim ChildForm As Boolean = False
在创建子窗体的地方:
ChildFormThere = True
在子窗体的“离开”事件中,我认为我可以这样做:
Me.MdiParent.ChildFormThere = False
但它不识别 ChildFormThere 变量...那怎么做呢?
【问题讨论】:
标签:
vb.net
singleton
global-variables
mdichild
mdiparent
【解决方案1】:
这样的事情怎么样。这个想法是,如果表单已经创建,则切换到它,否则创建一个。这假设您在创建子表单时正确设置了 mdiParent。此代码需要在 mdiParent 上运行,或者需要对其进行引用才能访问 MdiChildren 属性。
For Each f In Me.MdiChildren
If TypeOf (f) Is Form1 Then
f.Show()
Exit Sub
End If
Next
Dim frm As New Form1
frm.Show()
【解决方案2】:
也许不是:
dim ChildFormThere as Boolean = False ' Or True
你可以这样做:
dim ChildForm as New ChildFormClass
' On Create Button Click:
ChildForm.Visible = True
这样它总是同一个实例,所以你必须简单地管理它是否可见。