如何在VB.NET中为局部变量添加事件处理程序 [英] How to add event handler to local variable in VB.NET
问题描述
由于它始终是本地变量,如何添加事件处理程序?我搜索了自己,发现了一些东西,但我无法真正弄清楚...
事件的代码,中的一个字段MyDialog
:
public Event ObjectCreated(ByRef newMyObject as MyObject)
主窗体调用对话框的代码:(不介意语法)
<$作为新的MyDialog()
dialog.ShowDialog(Me)
AddHandler ObjectCreated,(我在这里放什么?)//或者如何添加一个处理程序?
正如你所看到的,我坚持如何为我的事件添加一个处理程序。有人可以帮我吗
为了保持一致性,建议您使用相同的源和事件将模型视为所有系统事件处理程序。
创建自己的类继承自EventArgs,如下:
公共类MyObjectEventArgs
继承EventArgs
公共属性EventObject As MyObject
结束类
然后声明你的事件和一个处理方法,如:
Public Event ObjectCreated As EventHandler(Of MyObjectEventArgs)
Private Sub Container_ObjectCreated(ByVal sender As Object,ByVal e As MyObjectEventArgs)
'处理程序代码在这里
End Sub
然后使用以下方式将处理程序附加到您的活动中:
AddHandler ObjectCreated,AddressOf Container_ObjectCreated
此外,您可以使用处理
附加到从主窗体(假设名称MainForm)引发的事件,如下所示:
私有子MainForm_ObjectCreated(ByVal sender As Object,ByVal e As MyObjectEventArgs)处理MainForm.ObjectCreated
'处理程序代码这里
End Sub
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...
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
这篇关于如何在VB.NET中为局部变量添加事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!