VB.net从另一个类访问类属性

时间:2013-08-15 03:48:37

标签: vb.net

我需要一些帮助让我的头脑包裹实例和类。在下面的代码中,我有一个main_form,我也在将一个user_control加载到main_form中。我有一个属于main_form的属性,我将设置名为obj的数据。我的问题是当我在user_control中工作时,我如何进入并设置main_form的obj属性。我尝试了main_form.obj,但我不断收到错误“对象引用没有设置为对象的实例”。所以,我不知道该怎么做。这是愚蠢的代码

Public Class FormControlClass
Private _obj As New objCollection

Public Property obj As objCollection
    Get
        Return _obj
    End Get
    Set(ByVal value As objCollection)
        _obj = value
    End Set
End Property

'Load User Control Into Form from here.
me.controls.add('UserControl')

End Class


Public Class UserControlClass

'Access the obj property in the form control class from here.
FormControlClass.obj = 1

End Class

1 个答案:

答案 0 :(得分:0)

即使你可以做你想做的事情,也不是一个好主意,因为你会将你的用户控件与这个特定的形式结合起来,使得它在这种形式之外无用。

相反,您需要让您的用户控件生成表单可以订阅并处理自身的事件。换句话说,您希望让用户控件创建一个可以传递给表单的消息,如下所示:

Public Class UserControlClass
    ' Define event that will be raised by user control to anyone interested in handling the event
    Public Event UC_Button1Click()

    ' Mechanism to allow event to be raised by user control
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        RaiseEvent UC_Button1Click()
    End Sub
End Class

现在在表单类中,您需要为用户控件引发的事件添加处理程序,如下所示:

AddHandler userControl1.UC_Button1Click, AddressOf Button1_Click

最后,您将创建AddressOf语法中引用的方法,如下所示:

Public Sub Button1_Click(ByVal sender As Object, ByVal args As EventArgs)
    ' Do something here
End Sub