【问题标题】:Passing control from one class to an event handler from another class将控制从一个类传递给另一个类的事件处理程序
【发布时间】:2014-12-14 18:38:42
【问题描述】:

我在 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?

【问题讨论】:

  • 如果tick事件将引用一些控件,它应该作为成员变量提供给TheClass。您不会将任何内容传递给事件处理程序

标签: vb.net class parameter-passing


【解决方案1】:

如果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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多