dimanche 22 novembre 2020

How to properly add a event-handler to a event-handler list of a control in .NET

I'm trying to write a class whose constructor expects a reference to a control / component, and the name of an event within the control class. The purpose is to dynamically subscribe to the specified event from the instance of the referenced control by adding a event-handler at runtime:

Public NotInheritable Class ExampleType(Of T As Component)

    Public ReadOnly Property Target As T

    Public Sub New(target As T, eventName As String)
        Me.Target = target

        Dim eventsProperty As PropertyInfo = 
            GetType(Component).GetProperty("Events", 
                                           BindingFlags.DeclaredOnly Or 
                                           BindingFlags.ExactBinding Or 
                                           BindingFlags.Instance Or 
                                           BindingFlags.NonPublic, 
                                           DefaultBinder, 
                                           GetType(EventHandlerList), 
                                           EmptyTypes, Nothing)
      
        Dim eventHandlerList As EventHandlerList = 
            DirectCast(eventsProperty.GetValue(target, BindingFlags.Default, 
                                               DefaultBinder, Nothing, 
                                               CultureInfo.InvariantCulture), 
                                               EventHandlerList)

        Dim eventHandler As New EventHandler(AddressOf Me.Target_Handler)
        eventHandlerList.AddHandler(eventName, eventHandler)
    End Sub

    Private Sub Target_Handler(sender As Object, e As EventArgs)
        Console.WriteLine("Test")
    End Sub

End Class

Example usage:

Dim target As NumericUpDown = Me.NumericUpDown1
Dim eventName As String = NameOf(NumericUpDown.ValueChanged)

Dim example As New ExampleType(Of NumericUpDown)(target, eventName)

The problem is that in the example above the Target_Handler method is never reached when in this case the Me.NumericUpDown1.ValueChanged event is raised, unless I invoke the event-handler method from code (with: eventHandlerList(eventName).DynamicInvoke(target, Nothing))

What I'm doing wrong?, how to solve my problem?. Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire