這種方法沒有什麼錯。是的,你確實想要清理右側面板的舊內容。這通常是不正確的,使用面板的Controls.Clear()方法是一個非常討厭的資源泄漏。你有配置舊的控件。所以,大致如下:
Private Sub DisplaySelection(uc As UserControl)
Do While Panel2.Controls.Count > 0
Panel2.Controls(0).Dispose()
Loop
Panel2.Controls.Add(uc)
End Sub
這可以任意擴展。例如,一個很好的黑客就是在面板中放置一個表格,這樣可以很容易地設計你的用戶界面。將一個TreeView放置在左側,它旁邊的面板完全停靠。爲每個表單添加節點,將每個節點的Tag屬性設置爲表單的名稱(如「Form2」等)。添加AfterSelect事件處理程序:
Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
DisplaySelection(CStr(e.Node.Tag))
End Sub
的DisplaySelection()方法現在需要動態地創建起的名字Form對象並將其嵌入在面板中。該代碼可能如下所示:
Private Sub DisplaySelection(formName As String)
If String.IsNullOrEmpty(formName) Then
Throw New InvalidOperationException("You forgot to set the Tag property")
End If
'' Ignore if that form is already displayed
If Panel1.Controls.Count > 0 AndAlso Panel1.Controls(0).GetType().Name = formName Then Return
'' Destroy the currently displayed form, if any
Do While Panel1.Controls.Count > 0
Panel1.Controls(0).Dispose()
Loop
'' Generate full type name if necessary to get, say, "WindowsApplication.Form2"
If Not formName.Contains(".") Then formName = Me.GetType().Namespace + "." + formName
Dim frm = CType(System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(formName), Form)
If frm Is Nothing Then Throw New InvalidOperationException("Cannot find form " + formName)
'' Embed the form in the panel as a child control
frm.TopLevel = False
frm.FormBorderStyle = FormBorderStyle.None
frm.Visible = True
frm.Dock = DockStyle.Fill
Panel1.Controls.Add(frm)
End Sub
如果您通過代碼創建面板,則可以在完成後輕鬆「處理」它們。但是如果你再次調用它,你將不得不重新創建它。 –