Reputation: 159
I'm trying to understand how I can expose an event in this situation:
When the event is raised from class C, is possible to manage it directly from class A?
Public Class C
Public Event E()
Public Sub Function_of_C()
RaiseEvent E()
End Sub
End Class
Public Class B
Public WithEvents m_C as new C
End Class
Public Class A
Public WithEvents m_B as new B
Private Sub Function_of_A() Handles m_B.m_C.E '<-- Doesn't work
'Do something
End Sub
End Class
Upvotes: 0
Views: 366
Reputation: 9981
Just as a supplement to Steve's answer, here's an example of the common design pattern to forward events:
Public Class Doorbell
Public Event Ding As EventHandler
Protected Overridable Sub OnDing(e As EventArgs)
RaiseEvent Ding(Me, e)
End Sub
Friend Sub RaiseDing()
Me.OnDing(EventArgs.Empty)
End Sub
End Class
Public Class House
Implements IDisposable
Public Event DoorbellDing As EventHandler
Public Property Doorbell() As Doorbell
Get
Return Me.m_doorbell
End Get
Set(value As Doorbell)
If (Not value Is Me.m_doorbell) Then
Me.UnookDoorbell()
Me.m_doorbell = value
Me.HookDoorbell()
End If
End Set
End Property
Public Sub Dispose() Implements IDisposable.Dispose
Me.UnookDoorbell()
End Sub
Private Sub HandleDoorbellDing(sender As Object, e As EventArgs)
Me.OnDoorbellDing(e)
End Sub
Private Sub OnDoorbellDing(e As EventArgs)
RaiseEvent DoorbellDing(Me, e)
End Sub
Private Sub HookDoorbell()
If (Not Me.m_doorbell Is Nothing) Then
AddHandler Me.m_doorbell.Ding, AddressOf Me.HandleDoorbellDing
End If
End Sub
Private Sub UnookDoorbell()
If (Not Me.m_doorbell Is Nothing) Then
RemoveHandler Me.m_doorbell.Ding, AddressOf Me.HandleDoorbellDing
End If
End Sub
Private m_doorbell As Doorbell
End Class
Upvotes: 0
Reputation: 216293
As explained in the comment to your question. You need to bubble up the event in class B when it receives from C.
Sub Main
Dim test = new A()
End Sub
Public Class C
Public Event E()
Public Sub Function_of_C()
RaiseEvent E()
End Sub
End Class
Public Class B
Public WithEvents m_C as new C
Public Event E()
Public Sub FnB() Handles m_C.E
Console.WriteLine("In B received Event from C")
RaiseEvent E()
End Sub
Public Sub TriggerC()
Console.WriteLine("In B TriggerC, call C.Function_Of_C")
m_C.Function_Of_C()
End Sub
End Class
Public Class A
Public WithEvents m_B as new B
Private Sub Function_of_A() Handles m_B.E
Console.WriteLine("In A received Event from B")
End Sub
public Sub New()
Console.WriteLine("In A constructor, call B.TriggerC")
m_b.TriggerC()
End Sub
End Class
Upvotes: 2