How to create a global event?

和自甴很熟 提交于 2021-02-11 13:03:39

问题


I have a global variable g_user as string and a Label lb_welcome to show username, How can i create a global event when g_user changed then will trigger a function

Private Sub Login()
    g_user = VerifyUser(id,password)
    lb_welcome.Text = $"Welcome {g_user}"
End Sub 

I try to do something like this:-

   Private Sub RefreshLabel()
        lb_welcome.Text = $"Welcome {g_user}"
   End Sub

   Private Sub g_user_Changed(sender As Object, e As EventArgs) Handles g_user.Changed
        RefreshLabel()
   End Sub

Above is just an example, lb_welcome.Text contain many global variable, I always have to manually add the function when a variable changed, so is it possible to create a global event to help me run the function automatically?


回答1:


You need to define a public Event in your Module which is raised if one of your properties (here g_user) is changed:

Public Module MyModule      
    Public Event Changed As EventHandler(Of ChangedEventArgs)

    Private _user As String
    Public Property g_user As String
        Get
            Return _user
        End Get
        Set(value As String)
            _user = value
            raisePropertyChanged("g_user", value)
        End Set
    End Property

    Private Sub raisePropertyChanged(propertyName As String, value As String)
        RaiseEvent Changed(Nothing, New ChangedEventArgs() With {.PropertyName = propertyName, .Value = value})
    End Sub
End Module

The EventArgs are pretty straight forward:

Public Class ChangedEventArgs
    Inherits EventArgs

    Public PropertyName As String
    Public Value As String
End Class

In your form hook the event and react to it:

Public Class Form1

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        AddHandler MyModule.Changed, AddressOf RefreshLabel

    End Sub

    Private Sub RefreshLabel(s As Object, e As ChangedEventArgs)
        If e.PropertyName = "g_user" Then
            lb_welcome.Text = $"Welcome {e.Value}"
        Else
            '...
        End If
    End Sub
End Class


来源:https://stackoverflow.com/questions/42409361/how-to-create-a-global-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!