我正在尝试将活动记录器添加到我的应用程序中。我希望保持我的代码干净,所以只想在我的代码中声明当前活动一次,然后它在lblStatus中显示它并更新日志文件。我想这样做:
我按照我的正常形式传递它:
LogActivity.LogActivity(Me, "Checking program directories...")
这是正在做的工作的潜艇。
Public Sub LogActivity(FormID As Form, ByVal ActivityDescription As String)
'Log Activity code is here
'Update Status Label on form
FormID.lblStatus = ActivityDescription
end sub
但Visual Studio不理解语法,我可以理解为什么,但我不确定如何正确地做到这一点。
'lblStatus'不是'Form'的成员
但是,我的所有表单都会调用这个子,所以我真的需要我的代码来理解哪个表单称为sub并且特别更新该表单上的lbl。
我可以像这样检查表单的名称:
If Form.Name = "Main_Loader" Then
Main_Loader.lblStatus = ActivityDescription
elseif Form.Name = "..." then
end if
但是,这不是很干净,似乎不是正确的方式......任何人都可以建议吗?
答案 0 :(得分:1)
您可以使用自定义事件。需要报告的信息的表单订阅了具有LogActivity的表单上的事件。
Public Class frmActivity 'name of class is an example
Private log As New LogClass
Public Event LogActivity(ActivityDescription As String, log As LogClass)
'somewhere in code raise this event and send to info to main form
Private Sub SomeEventSub()
RaiseEvent LogActivity("some status", log)
End Sub
'...
End Class
Public Class frmMain 'name of class is an example
Private Sub btnGetActivity() Handles btnGetActivity.Click
Dim frm As New frmActivity
Addhandler frm.LogActivity, AddressOf LogActivity
frm.Show()
End SUb
Private Sub LogActivity(ActivityDescription As String, log As LogClass)
lblStatus = ActivityDescription
'then use the log variable to store the log data
End Sub
'...
End Class
答案 1 :(得分:1)
假设Label在表单的 ALL 上被称为“lblStatus”,您可以像这样简单地使用Controls.Find():
Public Sub LogActivity(FormID As Form, ByVal ActivityDescription As String)
Dim matches() As Control = FormID.Controls.Find("lblStatus", True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is Label Then
Dim lbl As Label = DirectCast(matches(0), Label)
lbl.Text = ActivityDescription
End If
End Sub