English 中文(简体)
如何将一个子对象在通用列表中的事件传递给父级对象?
原标题:
  • 时间:2008-11-11 11:09:49
  •  标签:

这是我的示例代码:

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 child`s in the parent object? using withevents on the _child object gives me only the events from the List(of T) object.

最佳回答

如果我是你,我会使用聚合类型列表在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
  }
}
问题回答

暂无回答




相关问题
热门标签