如何将事件从通用列表中的子对象传递给父对象?

时间:2008-11-11 11:09:50

标签: vb.net generics event-handling

这是我的示例代码:

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

如何处理父对象中某个子节点引发的事件? 在_child对象上使用withevents只给我List(of T)对象的事件。

TIA

1 个答案:

答案 0 :(得分:1)

如果我是你,我会使用聚合类型列表在Parent中实现IList,但是在IList.Add上订阅Child事件并在Remove上订阅unsubscibing。这样的事情(抱歉C#语法)。

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
  }
}