2017-07-05 58 views
-1

我有一個自定義的FlowLayoutPanel:一個「AlbumFlowLayout」,它從FlowLayoutPanel繼承並用於存放UserControls(「AlbumItems」)的集合。通常情況下,這將駐留在形式(「FrmMain」)上,使項目的層次是:當子控件被實例化時添加一個事件處理程序

Form ("FrmMain") 
    AlbumFlowLayout ("AlbumFlowLayout1") 
    AlbumItems (1 or more) 

[有什麼辦法/什麼是協議]添加一個「WasClicked」處理程序創建的AlbumItem每當它創建/添加到AlbumFlowLayout?

理想情況下,我想封裝AlbumFlowLayout中的處理程序構造代碼,以便在FrmMain中的代碼執行新的AlbumItem的AlbumFlowLayout.Controls.Add時自動發生,而不是在FrmMain add中添加第二行處理器添加控件之前,例如:

Dim myItem As New AlbumItem 

AddHandler myItem.WasClicked, AddressOf AlbumFlowLayout1.AlbumItem_WasClicked 
AlbumFlowLayout1.Controls.Add(myItem) 

謝謝! -Pete

+0

容器控件包含一個ControlAdded事件,您可以在其中進行連接。不知道這是否符合*自動* – Plutonix

+0

完美!這正是我需要的。如果您願意,請添加您的答案作爲答案,我會將其標記爲正確答案。 – pbickford

回答

0

Plutonix有解決方案。以下是最終代碼的樣子:

Partial Public Class AlbumFlowLayout 
    Inherits FlowLayoutPanel 

    ' A FlowLayoutPanel for handling collections of AlbumItems 

    Public SelectedItems As New List(Of String) 
    ' Holds IDs of currently selected items 


    Private Sub AlbumFlowLayout_ControlAdded(sender As Object, e As ControlEventArgs) Handles Me.ControlAdded 
    ' Wire up each user item as it's added so that it will pass its 
    ' Wasclicked up to here 

    Dim myAlbumItem As AlbumItem = e.Control 
    AddHandler myAlbumItem.WasClicked, AddressOf Me.AlbumItem_WasClicked 
    End Sub 

    ' Other methods... 
    ' ... 

    Public Sub AlbumItem_WasClicked(ByVal sender As Object, e As EventArgs) 
    ' Deselects all previously selected items. Doing this via a List to 
    ' Allow for expansion item where we permit multi-selection via 
    ' Control-key or the like; currently is single-select 

    Dim myItem As AlbumItem = sender 

    For Each itm As String In SelectedItems 
     If itm <> myItem.Name Then 
      DirectCast(Me.Controls(itm), AlbumItem).IsSelected = False 
     End If 
    Next 

    SelectedItems.Clear() 
    SelectedItems.Add(myItem.Name) 
    End Sub 
End Class 
相關問題