我有一个全局变量g_user作为字符串和标签lb_welcome显示用户名,当g_user更改时,我该如何创建一个全局事件,然后将触发函数
Private Sub Login()
g_user = VerifyUser(id,password)
lb_welcome.Text = $"Welcome {g_user}"
End Sub
我尝试做这样的事情: -
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
上面只是一个示例,lb_welcome.text包含许多全局变量,当变量更改时,我总是必须手动添加函数,因此可以创建一个全局事件来帮助我自动运行该函数?
您需要在模块中定义公共事件,如果您的属性之一(此处g_user)更改了:
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
Eventargs非常简单:
Public Class ChangedEventArgs
Inherits EventArgs
Public PropertyName As String
Public Value As String
End Class
在您的表格中挂钩事件并对此做出反应:
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