Assigning event handlers to another object

D

David Anton

Using 'WithEvents' in VB, the event handlers for an object remain intact
after a re-assignment (see the following), but I can't find a convenient way
to do this in C#:
Public Class Form1
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents Button2 As System.Windows.Forms.Button
Friend WithEvents test As System.Windows.Forms.Button

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
test = Button1
End Sub

Private Sub button_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles test.Click
MsgBox(CType(sender, Button).Name)
If test Is Button1 Then
'Button2 will now react to all the events defined for 'test':
test = Button2
Else
'Button1 will now react to all the events defined for 'test':
test = Button1
End If
End Sub
End Class

I know that I can hard-code the event wireups in C#:
test.Click -= button_Click;
test = Button2;
test.Click += button_Click;

but obviously this becomes unworkable when you know that more event handlers
than just 'Click' are involved.
--
http://www.tangiblesoftwaresolutions.com
C++ to C#
C++ to VB
C++ to Java
Instant C#: VB to C#
Instant VB: C# to VB
Instant C++: VB or C# to C++/CLI
Java to VB & C# Converter: Java to VB or C#
 
J

Jon Skeet [C# MVP]

David Anton said:
Using 'WithEvents' in VB, the event handlers for an object remain intact
after a re-assignment (see the following), but I can't find a convenient way
to do this in C#

You'd need to do the same as VB does - turn the fields into properties,
and in the setter unsubscribe from the old value's events and subscribe
to the new value's events.
 
D

David Anton

Thanks Jon.
I was hoping for a more direct conversion that we could incorporate into
Instant C#, but I'll use your advice.
--
http://www.tangiblesoftwaresolutions.com
C++ to C#
C++ to VB
C++ to Java
Instant C#: VB to C#
Instant VB: C# to VB
Instant C++: VB or C# to C++/CLI
Java to VB & C# Converter: Java to VB or C#
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top