将控制从一个类传递到另一个类的事件处理程序

时间:2014-12-14 18:38:42

标签: vb.net class parameter-passing

我在Form1中有一个TextBox1。我需要将它传递给另一个类(在类库/另一个项目中)。因此,该类实例可以修改整个类中的TextBox1内部(而不仅仅是范围)。对于我的问题,我需要将它传递给事件处理程序。

Public Class TheClass

    WithEvents Timer1 As New Timer

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Timer1.Tick

    End Sub

End Class

我可以考虑通过引用传递。但是,我找不到将TextBox1传递给该事件处理程序的方法。

如何让Timer1有权修改Form1中的TextBox1?

1 个答案:

答案 0 :(得分:0)

如果在TheClass之后创建Form1,您可以使用构造函数注入将Form1的引用传递给TheClass

Public Class TheClass

    Private WithEvents Timer1 As New Timer
    Private m_form1 As Form1

    Public Sub New (ByVal form1 as Form1)
        m_form1 = form1
    End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Timer1.Tick

        m_form1.TextBox1.Text = "tick"
    End Sub

End Class

请注意TextBox1必须是公开或朋友。


另一种方法是将公共事件添加到TheClass

Public Class TheClass

    Public Event Tick()

    Private WithEvents Timer1 As New Timer

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Timer1.Tick

        RaiseEvent Tick()
    End Sub

End Class

现在表单可以处理此事件。

' In Form1
Private WithEvents theObj As New TheClass

Private Sub theObj_Tick() _
    Handles theObj.Tick

    Me.Textbox1.Text = "tick"
End Sub

现在,您可以将Textbox1设为私有,TheClass不需要了解任何有关文本框的内容。

事件处理程序也可以有参数

' In TheClass
Public Event Tick(ByVal counter As Integer)

...

Counter += 1
RaiseEvent Tick(Counter)

' In Form1
Private Sub theObj_Tick(ByVal counter As Integer) _
    Handles theObj.Tick

    Me.Textbox1.Text = "counter = " & counter
End Sub