EventHandlers in VB: How to pass them around.
I was implementing an special
After a little bit of searching, I took a page out of the
In order to detect if YOUR class has event handlers attached, you need to create a Custom Event. Something like this:
Custom Events are available to VB programmers ever since .NET Framework 2.0 along with Visual Studio 2005, although it's not very used, due to the fact that simply declaring an event and using
But when we need something different, it's good to know it's available to us.
INotifyCollectionChanged
when I needed to know if the instance had event handlers attached.After a little bit of searching, I took a page out of the
ObservableCollecion(Of T)
in order to do it.In order to detect if YOUR class has event handlers attached, you need to create a Custom Event. Something like this:
Private __MyEventHandler as EventHandler
Public Custom Event MeEvent As EventHandler
AddHandler(ByVal value As EventHandler)
Dim handler2 As EventHandler
Dim myEventHandler = __MyEventHandler
Do
handler2 = canExecuteCommand
Dim handler3 = DirectCast( _
System.Delegate.Combine(handler2, value), _
EventHandler)
myEventHandler = Interlocked.CompareExchange( _
(__MyEventHandler), handler3, handler2)
Loop While (Not myEventHandler Is handler2)
__MyEventHandler = myEventHandler
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Dim handler2 As EventHandler
Dim myEventHandler = __MyEventHandler
Do
handler2 = canExecuteCommand
Dim handler3 = DirectCast( _
System.Delegate.Remove(handler2, value), _
EventHandler)
myEventHandler = Interlocked.CompareExchange( _
(__MyEventHandler), handler3, handler2)
Loop While (Not myEventHandler Is handler2)
__MyEventHandler = myEventHandler
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
If (__MyEventHandler IsNot Nothing) Then
__MyEventHandler.Invoke(sender, e)
End If
End RaiseEvent
End Event
Custom Events are available to VB programmers ever since .NET Framework 2.0 along with Visual Studio 2005, although it's not very used, due to the fact that simply declaring an event and using
AddHanlder
, RemoveHandler
and RaiseEvent
solve most of day-to-day event problems.But when we need something different, it's good to know it's available to us.
0 Comments:
Post a Comment