參考:有 20 多個面板在可見性更改時需要此事件,所有面板都具有相同的命名約定 project_x(x 是面板編號)
我無法對這段代碼進行期望與現實,因為我無法找到如何最好地做到這一點。
進一步說明:在由外部類控制的事件 'VisibleChanged' 上,我們想要一種在更短的代碼中動態應用它的方法。當然我們可以做到這一點并對所有內容進行硬編碼并且它作業正常,但我想知道是否有辦法動態地做到這一點。
Private Sub project_1_VisibleChanged(sender As Object, e As EventArgs) Handles project_1.VisibleChanged
Try
If project_1.Visible = True Then
'There's code here but it's been omitted
End If
Catch ex As Exception
End Try
End Sub
uj5u.com熱心網友回復:
您可以在表單加載中找到所有相關面板并將每個面板訂閱到單個事件處理程式方法
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'assuming the panels are on the main form you would use Me
'else you would use the name of the control that the panel is located within - e.g. SomeControlName.Controls...
Dim panels = Me.Controls.OfType(Of Panel).Where(Function(panel) panel.Name.StartsWith("project_"))
For Each panel In panels
AddHandler panel.VisibleChanged, AddressOf PanelVisibilityChanged
Next
End Sub
Private Sub PanelVisibilityChanged(sender As Object, e As EventArgs)
Dim panel = DirectCast(sender, Panel)
Try
If panel.Visible Then
'assuming the picture box is within the panel
Dim pictureBox = panel.Controls.Find($"{panel.Name}_img", True)(0)
'There's code here but it's been omitted
End If
Catch ex As Exception
End Try
End Sub
uj5u.com熱心網友回復:
是的,像這樣:
Private Sub panels_VisibleChanged(sender As Object, e As EventArgs) _
Handles project_1.VisibleChanged,
project_2.VisibleChanged,
project_3.VisibleChanged,
project_4.VisibleChanged,
project_5.VisibleChanged,
project_6.VisibleChanged,
project_7.VisibleChanged
Dim ctrl As Panel = DirectCast(sender, Panel)
Try
If ctrl.Visible = True Then
'There's code here but it's been omitted
End If
Catch ex As Exception
End Try
End Sub
還有其他幾種方法可以做到這一點。這可能是最干凈的 VB.net 和您的情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/402850.html
標籤:
上一篇:為發件人物件處理程式創建函式
