vb.netevent-handlingraiseevent

Handling property changed from another class in vb.net


I have a class like below which contains my global variables as property. I made this "ModelFullPath" from variable to property because i dont know how to raise events with the variable changes.(If you have more logic suggestions i'll appreciate.)

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

In my other class i have "Button2" which gets the string value textbox and sets the my Globals' ModelFullPath property according to textbox1.Text value. On the other hand Button1 is writing Globals.ModelFullPath property to a label1.text value.

In here i'd like to put an event if ModelFullPath is changed, i'd like to make some actions like changing tool's background colors etc. Currently i set it the show "It Changed" with Message Box. But the main problem is i cant handle it from another class like below.

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

How can handle Globals.VariableChanged event? Because it doesnt recognize this event.


Solution

  • You need to use AddHandler() to wire up the event. The Load() event of your Form is a good place to do that:

    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