0

我有一个像下面这样的类,其中包含我的全局变量作为属性。我从变量到属性制作了这个“ModelFullPath”,因为我不知道如何通过变量更改引发事件。(如果您有更多逻辑建议,我将不胜感激。)

Public Class Globals
    Private Shared _modelfullpath As String = String.Empty
    Public Shared Event ModelPathChanged(ByVal _modelfullpath As String)

    Public Shared Property ModelFullPath() As String
        Get
            Return _modelfullpath
        End Get
        Set(ByVal value As String)
            _modelfullpath = value
            RaiseEvent ModelPathChanged(_modelfullpath)
        End Set
    End Property
    Public Shared Sub TestIt() Handles MyClass.ModelPathChanged
        ' Some codes in here
        MessageBox.Show("It Changed")
    End Sub
End Class

在我的另一个类中,我有“Button2”,它获取字符串值文本框并根据 textbox1.Text 值设置我的 Globals 的 ModelFullPath 属性。另一方面 Button1 正在将 Globals.ModelFullPath 属性写入 label1.text 值。

在这里,如果 ModelFullPath 发生更改,我想放置一个事件,我想做一些操作,例如更改工具的背景颜色等。目前我将其设置为使用消息框显示“它已更改”。但主要问题是我无法从下面的另一个类中处理它。

Public Class MainTool
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Label1.Text = Globals.ModelFullPath
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Globals.ModelFullPath = TextBox1.Text
    End Sub
    Private Sub VariableChanged() Handles Globals.VariableChanged
        Globals.TestIt()
    End Sub
End Class

如何处理Globals.VariableChanged事件?因为它不承认这个事件。

4

1 回答 1

1

您需要使用AddHandler()来连接事件。表单的 Load() 事件是一个很好的地方:

Public Class MainTool

    Private Sub MainTool_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddHandler Globals.ModelPathChanged, AddressOf Globals_ModelPathChanged
    End Sub

    Private Sub Globals_ModelPathChanged(_modelfullpath As String)
        TextBox1.Text = _modelfullpath
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Globals.ModelFullPath = "Hello!"
    End Sub

End Class
于 2019-01-13T15:35:22.790 回答