2017-01-22 37 views
0

我正在尝试将活动记录器添加到我的应用程序中。我希望保持我的代码清洁,因此只想在我的代码中声明一次当前活动,然后将其显示在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”不是“形式”

不过的一员,我的所有形式将调用此子,所以我真的需要我的代码,以了解哪些形式称为子和更新特别是在那种形式上。

我可以只检查表单的名字是这样的:

If Form.Name = "Main_Loader" Then 
Main_Loader.lblStatus = ActivityDescription 
elseif Form.Name = "..." then 
end if 

但同样,这不是很干净,似乎不是正确的方法......谁能指教?

+0

'系统,Windows.Forms'是从基类所有形式都继承。它与“MyForm”或“Form1”不同或者你的表单类被命名。为了保持表单清洁的希望将通过传递UI元素而不是变量来破灭, – Plutonix

+0

为什么不在更新标签**之前**你打电话给你的记录器,你已经有了适当的范围。使用您的记录器类仅更新您的日志文件。它会让你无需弄清楚调用形式,并将你的FormId变量转换为你的日志类中的正确类型。 –

回答

1

假设标签被称为 “lblStatus” 上的形式ALL,你可以简单地使用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 
+0

绝对完美,正是我在寻找的感谢。 – user3516240

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