How to pass event from child to shared list to parent?

here is my example code:

Public Class Parent
    Private _TestProperty As String
    Private WithEvents _Child As IList(Of Child)

    Public Property Test() As String
        Get
            Return _TestProperty
        End Get
        Set(ByVal value As String)
            _TestProperty = value
        End Set
    End Property

    Public Property Child() As IList(Of Child)
        Get
            Return _Child
        End Get
        Set(ByVal value As IList(Of Child))
            _Child = value
        End Set
    End Property

    Private Sub eventHandler Handles _Child
End Class

Public Class Child
    Private _TestProperty As String
    Public Event PropertyChanged As EventHandler

    Friend Sub Notify()
        RaiseEvent PropertyChanged(Me, New EventArgs())
    End Sub

    Public Property Test() As String
        Get
            Return _TestProperty
        End Get
        Set(ByVal value As String)
            _TestProperty = value
            Notify()
        End Set
    End Property
End Class

      

how can I handle the event raised by one of the children in the parent? using withevents on the _child object only gives me events from the List (of T) object.

TIA

0


source to share


1 answer


If I were you, I would implement IList on Parent using an aggregated typed list, but subscribing to child events on IList.Add and unsubscibing on Remove. Something like this (sorry for the c # syntax).



class Child
{
  public event EventHandler MyEvent;
}

class Parent : IList<Child>
{
  List<Child> _list;

  // IList implementation
  // ...
  public void Add(Child item)
  {
     item.MyEvent += _ParentChildEventHandler;
     _list.Add(item);  
  }

  public void Remove(Child item)
  {
    item.MyEvent -= _ParentChildEventHandker;
    _list.Remove(item);
  }

  void _ParentChildEventHandler(object sender, EventArgs e)
  {
    Child child = (Child)sender;

    // write your event handling code here
  }
}

      

+1


source







All Articles