有没有人可以解释的动态解决方案?

Is there a Dynamic Solution to this that someone might be able to explain?

参考:有 20 个左右的面板在可见性更改时需要此事件,所有面板都具有相同的命名约定 project_x(x 是面板编号)

我无法对这段代码进行期望与现实对比,因为我找不到最好的方法。

进一步说明:对于由外部 Class 控制的事件 '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

是的,像这样:

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 和您的情况,这可能是最干净的。

您可以在表单加载中找到所有相关面板,并为每个面板订阅一个事件处理程序方法

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