从一对多关系中冒泡事件

时间:2013-11-05 23:27:26

标签: vb.net events event-handling

我可以像这样一对一的关系冒泡一个事件

Public Class Husband

    Public WithEvents Wife As Wife

    Public Sub WifeChangedLastName() Handles Wife.LastNameChanged
        MsgBox("Wife Changed Last Name")
    End Sub

End Class

Public Class Wife

    Public _LastName As String
    Public Property LastName As String
        Get
            Return Me._LastName
        End Get
        Set(ByVal Value As String)
            Me._LastName = Value
            Raise Event LastNameChanged(Me, EventArgs.Empty)
        End Set
    End Property

    Public Event LastNameChanged As EventHandler

End Class

但是我如何通过一对多关系做类似的事情呢?这是我到目前为止所做的:

Public Class Organization

    Public WithEvents Group As New Group 'A one-to-one relationship

    Public Sub PersonAddedToGroup() Handles Group.PersonAdded
        MsgBox("A person has been added to the group.") 'This works
    End Sub

    'I want to do something here when a person's name changes

End Class

Public Class Group

    Public WithEvents People As List(Of Person) 'A one-to-many relationship

    Public Sub Add(ByVal Person As Person)
        Me.People.Add(Person)

        RaiseEvent PersonAdded(Me, EventArgs.Empty)      
    End Sub

    Public Event PersonAdded As EventHandler

End Class

Public Class Person

    Private _Name As String
    Public Property Name As String
        Get
            Return Me._Name
        End Get
        Set(ByVal Value As String)
            Me._Name = Value
            RaiseEvent PersonChanged(Me, EventArgs.Empty)
        End Set
    End Property

    Public Event PersonChanged As EventHandler

End Class

我想处理组织内的PersonChanged事件。我该怎么做?

2 个答案:

答案 0 :(得分:1)

您需要为每个人添加事件处理程序......但它们都可以通过相同的方法处理。这就是我的建议。

  1. 更改PersonAdded事件以传递已添加的新Person对象。您需要更新您声明事件/处理程序的位置以包含此内容,我相信......

    'Inside Group.Add(person As Person)
    RaiseEvent PersonAdded(Me, person)  
    
  2. PersonAdded的事件处理程序中,订阅该特定人员的PersonChanged事件:

    Public Sub PersonAddedToGroup(person As Person) Handles Group.PersonAdded
        MsgBox("A person has been added to the group.") 'This works
        AddHandler person.PersonChanged, AddressOf OnPersonChanged
    End Sub
    
  3. 这样的东西应该能达到你想要的效果(这是粗略的代码,而不是在VS中测试)。如果要添加和删除人员,请记住事件可能导致内存泄漏(即,当订阅事件的对象消失时,您将要调用RemoveHandler。在这种情况下,Organization将可能比Person对象更长久,所以如果我没有弄错的话,这不是一个问题。

答案 1 :(得分:0)

我从LarsTech找到了answer。他建议使用(System.ComponentModel。)BindingList处理属性更改事件。