1

我需要一些帮助来了解实例和类。在下面的代码中,我有一个 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
4

1 回答 1

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
于 2013-08-15T03:59:25.950 回答