I have been using classes for a while but I am relatively new at creating events in my classes. Prior to using events, If I wanted to make a public class that was available throughout my project, I would create a global variable for the class and then I would initialize the class before I needed to use the class:
Public ClassMFTV As New ClassMachineFunctionsTimerVars
What I have tried:
Now that I am using Events, I found out that I can no longer use this method. To use the events, I need to include the keywords WithEvents in my class declaration:
Public WithEvents ClassMFTV As New ClassMachineFunctionsTimerVars
When I try this, I get the following error:
Handles clause requires a WithEvents variable defined in the containing type or one of its base types
If I move the class declaration to my startup form, the error goes away but then I can only access the class variables in that form. I need to be able to read and update the variables in my class throughout the project. What is the proper way of doing this plus being able to fire custom events?
Here is a portion of my class. I am mainly using the class to check for changes in a series of variables that get collected via a timer. When the variable changes, I trigger an event to update things like the GUI, a database, etc.
Public Class ClassMachineFunctionsTimerVars
'Raises events to update the machine function screens
Private _Var826 As Integer = -9999
Private _Var827 As Integer = -9999
Public Event Var826ChangedEvent()
Public Event Var827ChangedEvent()
Public Property Var826() As Integer
Get
Var826 = _Var826
End Get
Set(ByVal value As Integer)
If value <> _Var826 Then
_Var826 = value
RaiseEvent Var826ChangedEvent()
Else
_Var826 = value
End If
End Set
End Property
Public Property Var827() As Integer
Get
Var827 = _Var827
End Get
Set(ByVal value As Integer)
If value <> _Var827 Then
_Var827 = value
RaiseEvent Var827ChangedEvent()
Else
_Var827 = value
End If
End Set
End Property
End Class
Here is my code for handling the events:
Public Sub Var826ChangedEventFired() Handles ClassMFTV.Var826ChangedEvent
'Update the radio button
If Var826 = 0 Then
Me.RadioXMasterHole.Checked = True
FormOperatorCDC.RadioXMasterHole.Checked = True
Else
Me.RadioXSetPoint.Checked = True
FormOperatorCDC.RadioXSetPoint.Checked = True
End If
End Sub
Public Sub Var827ChangedEventFired() Handles ClassMFTV.Var827ChangedEvent
'Update the radio button
If Var827 = 0 Then
Me.RadioBNotTilted.Checked = True
FormOperatorCDC.RadioBNotTilted.Checked = True
Else
Me.RadioBTilted.Checked = True
FormOperatorCDC.RadioBTilted.Checked = True
End If
End Sub