How to add event handler to local variable in VB.NET

不羁岁月 提交于 2019-12-08 19:49:38

问题


I have a form in VB.NET that is used as a dialog in a mainform. Its instances are always locally defined, there's no field for it. When the user clicks the OK button in the dialog, it will fire an event with exactly one argument, an instance of one of my classes.

Since it is always a local variable, how can I add an event handler for that event? I've searched for myself and found something but I can't really figure it out...

Code for the event, a field in MyDialog:

public Event ObjectCreated(ByRef newMyObject as MyObject)

Code for the main form to call dialog : (never mind the syntax)

Dim dialog As New MyDialog()
dialog.ShowDialog(Me)
AddHandler ObjectCreated, (what do I put here?) //Or how do I add a handler?

As you can see I'm stuck on how to add a handler for my event. Can anyone help me? Preferrably with the best way to do it...


回答1:


It's recommended, for consistency, that you use the same source and event args model as all system event handlers.

Create your own class inheriting from EventArgs, as:

Public Class MyObjectEventArgs
    Inherits EventArgs

    Public Property EventObject As MyObject

End Class

Then declare your event, and a handler method, like:

Public Event ObjectCreated As EventHandler(Of MyObjectEventArgs)

Private Sub Container_ObjectCreated(ByVal sender As Object, ByVal e As MyObjectEventArgs)
    ' Handler code here
End Sub

Then attach the handler to your event using:

AddHandler ObjectCreated, AddressOf Container_ObjectCreated

Additionally, you can use the Handles to attach to the event raised from your main form (assuming the name MainForm), as below:

Private Sub MainForm_ObjectCreated(ByVal sender As Object, ByVal e As MyObjectEventArgs) Handles MainForm.ObjectCreated
    ' Handler code here
End Sub



回答2:


You need to write the subroutine that actually executes when the event is generated:

public Sub OnObjectCreated(ByRef newMyObject as MyObject)
   ...
End Sub

Then the handler is added:

AddHandler ObjectCreated, AddressOf OnObjectCreated

As a side note, ByRef does nothing here. All objects in VB are passed by reference. Only primitave variables (string, int, etc) by default use ByVal and can be set to ByRef



来源:https://stackoverflow.com/questions/10319121/how-to-add-event-handler-to-local-variable-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!