我有一个自定义的FlowLayoutPanel:一个“AlbumFlowLayout”,它继承自FlowLayoutPanel,用于保存UserControls(“AlbumItems”)的集合。通常,这将驻留在表单(“FrmMain”)上,以便项目的层次结构为:
Form ("FrmMain")
AlbumFlowLayout ("AlbumFlowLayout1")
AlbumItems (1 or more)
每当创建/添加到AlbumFlowLayout时,[有没有办法/什么是协议]为创建的AlbumItem添加“WasClicked”处理程序?
理想情况下,我想将处理程序构造代码封装在AlbumFlowLayout中,以便每当FrmMain中的代码执行新AlbumItem的AlbumFlowLayout.Controls.Add时自动发生,而不是在FrmMain中添加第二行添加添加控件之前的处理程序,例如:
Dim myItem As New AlbumItem
AddHandler myItem.WasClicked, AddressOf AlbumFlowLayout1.AlbumItem_WasClicked
AlbumFlowLayout1.Controls.Add(myItem)
谢谢! -Pete
答案 0 :(得分: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