Handle Events of Object defined in another class/file

后端 未结 1 1058
醉酒成梦
醉酒成梦 2021-01-14 06:00

I have a VB.NET program where I have multiple forms and some variables that I want to access on all the forms, so I\'ve created a module file that contains some public varia

1条回答
  •  离开以前
    2021-01-14 06:52

    The key is the part of the message: requires a WithEvents variable defined in the containing type. Your foo is not defined in the containing type (your Form in this case). There are two ways to do this.

    Use the module/global declaration to provide scope foro the Foo object:

    Public mainFoo As FooBar
    

    It really only needs to be Friend, but since there is nothing to subscribe to events here, it doesnt need to be WithEvents. Forms/objects which just need access to Foo (not the events) can reference this mainFoo object.

    Next, any form or class which wishes to subscribe to Foo events, does need a local WithEvents variable set to the global object:

    Private WithEvents myFoo As FooBar    ' variable declaration
    
    myFoo = mainFoo       ' set myFoo to reference the real object
    

    The advantage to this method is that in the form code, you should be able to select myFoo from the menu on the left, then the FooEvent from the menu on the right for VB/VS to insert the correct event handler as it does with control events:

    Private Sub myFoo_FooChanged(sender As Object, newFoo As String) _
           Handles myFoo.FooChanged
    

    This other method is slightly simpler, just use AddHandler to manually hook up that main variable:

    AddHandler mainFoo.FooChanged, AddressOf sub_FooChanged
    

    It prevents having to create a local WithEvents variable, but it also prevents VS from creating the Event procedures for you.

    0 讨论(0)
提交回复
热议问题