处理 属性 已从 vb.net 中的另一个 class 更改

Handling property changed from another class in vb.net

我有一个如下所示的 class,其中包含我的全局变量 属性。我将此 "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

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

如果 ModelFullPath 发生更改,我想在此处放置一个事件,我想执行一些操作,例如更改工具的背景颜色等。目前我将其设置为带有消息框的显示 "It Changed"。但主要问题是我无法从另一个 class 处理它,如下所示。

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事件?因为它不识别这个事件。

您需要使用 AddHandler() 来连接事件。 Form 的 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