-1

这是我的示例代码:

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) 对象的事件。

蒂亚

4

1 回答 1

1

如果我是你,我会使用聚合类型列表在 Parent 中实现 IList,但在 IList.Add 上订阅 Child 事件并在 Remove 上取消订阅。像这样的东西(对不起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
  }
}
于 2008-11-11T11:33:52.693 回答