0

我有一堆要添加到单个父面板的面板,我想将事件侦听器添加到所有面板,但直到它们全部添加到父面板之后(因为我不希望事件侦听器触发每次添加新面板时)。所以我使用以下代码:

   Dim temp_object As question_bar = Nothing
   For Each q As Object In review_holder.Controls
       If TypeOf q Is question_bar Then
          temp_object = q
          AddHandler temp_object.Resize, AddressOf temp_object.resize_me
       End If
   Next

   For Each q As Object In review_holder.Controls
      If TypeOf q Is question_bar Then
         temp_object = q
         temp_object.resize_me()
      End If
   Next

但我注意到 resize_me() 子例程会为每个控件触发两次。我只希望它开火一次。所以我用这段代码追踪了它

MsgBox((New System.Diagnostics.StackTrace).GetFrame(1).GetMethod.Name)

我看到每次调用它的调用方法都是这个子例程和_Lambda$_365。那是什么呀?我怎样才能知道它来自哪里?

顺便说一句,这是一个使用 VS2012 的 winforms 应用程序。

编辑 - - - - - - - - - - - - - - - - - - - - - - - - - ----------------------

Public Sub resize_me()

 MsgBox((New System.Diagnostics.StackTrace).GetFrame(1).GetMethod.Name)

 If Me.minimized = True Then
    Me.Height = 0
    Exit Sub
 End If

 number_panel.Width = my_parent.number_width
 number_text.Width = my_parent.number_width
 number_separator.Left = number_panel.Right
 question_panel.Left = number_separator.Right
 question_panel.Width = question_panel.Parent.Width * initial_question_width + (question_padding * 2)


End Sub
4

1 回答 1

0

当您在调整大小事件中时,改变大小属性可以解释为什么您的代码会再次被调用。通常我会尽量避免这种情况,但这并不总是可能的。在这些情况下,一个作为标志来阻止重新进入的全局变量可以挽救这一天

Dim insideResize As Boolean

Public Sub resize_me()

 if insideResize = True Then
     Exit Sub
 End if

 insideResize = True
 Try
    If Me.minimized = True Then
       Me.Height = 0
       Exit Sub
    End If

    number_panel.Width = my_parent.number_width
    number_text.Width = my_parent.number_width
    number_separator.Left = number_panel.Right
    question_panel.Left = number_separator.Right
    question_panel.Width = question_panel.Parent.Width * initial_question_width + (question_padding * 2)
  Finally
    insideResize = False
  End Try

End Sub

为了保持这种模式的安全,请记住始终使用 Try/Finally 块,以确保当您退出 Resize 事件时,全局标志正确设置回 false。

于 2015-06-08T19:57:05.940 回答