从一对多关系中冒泡事件



我可以像这样从一对一的关系中冒出一个事件

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 事件。 我该怎么做?

您需要

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

  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
    

这样的事情应该完成你想要的(这是粗略的代码,而不是在VS中测试)。如果要添加和删除人员,请记住事件可能导致内存泄漏(即,当订阅事件的对象消失时,您需要调用RemoveHandler。在这种情况下,Organization可能会比Person对象更持久,所以如果我没记错的话,这不是什么大问题。

我从LarsTech找到了答案。 他建议使用(System.ComponentModel)。处理属性更改事件的绑定列表。

相关内容

  • 没有找到相关文章

最新更新