Inotify更改为另一个类或对象

时间:2012-05-04 19:53:57

标签: vb.net inotifypropertychanged

我处于一个小小的修复中,我有一个如下课程。

Public Class Bill
    Public prime As BillPrime
    Public items As System.Collections.ObjectModel.ObservableCollection(Of ItemDetails)
    Public status As New BillStatus
    Public Sub New()
        prime = New BillPrime
        items = New System.Collections.ObjectModel.ObservableCollection(Of ItemDetails)
        status = New BillStatus
    End Sub
End Class

如果prime中的任何ItemDetails对象发生更改,如何更新items中的某些x值。

请问如何解决问题?

2 个答案:

答案 0 :(得分:3)

尝试使用BindingList(of T),然后您可以收听更改事件:

Imports System.ComponentModel

Public Class Bill
  Public prime As BillPrime
  Public WithEvents items As BindingList(Of ItemDetails)
  Public status As New BillStatus
  Public Sub New()
    prime = New BillPrime
    items = New BindingList(Of ItemDetails)
    status = New BillStatus
  End Sub

  Public Sub items_ListChanged(ByVal sender As Object, ByVal e As ListChangedEventArgs)  Handles items.ListChanged
    prime.X = "something"
  End Sub
End Class

这需要您的课程实施INotifyPropertyChanged

Public Class ItemDetails
  Implements INotifyPropertyChanged

  Public Event PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged

  Private _DetailOne As String

  Property DetailOne() As String
    Get
      Return _DetailOne
    End Get
    Set(ByVal value As String)
      _DetailOne = value
      RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("DetailOne"))
    End Set
  End Property

End Class

答案 1 :(得分:1)

ItemDetails类需要在其任何属性发生更改时引发事件。我建议在ItemDetails类上实现INotifyPropertyChanged接口,但是你可以实现自己的事件。然后,您需要为每个ItemDetails.PropertyChanged事件添加一个事件处理程序,因为它被添加到列表中,并从列表中删除每个项目时删除处理程序。例如:

Public Class Bill
    Public prime As BillPrime
    Public items As System.Collections.ObjectModel.ObservableCollection(Of ItemDetails)
    Public status As New BillStatus

    Public Sub New()
        prime = New BillPrime
        items = New System.Collections.ObjectModel.ObservableCollection(Of ItemDetails)
        AddHandler items.CollectionChanged, AddressOf items_CollectionChanged
        status = New BillStatus
    End Sub

    Private Sub items_CollectionChanged(sender As Object, e As NotifyCollectionChangedEventArgs)
        For Each i as ItemDetails in e.NewItems
            AddHandler i.PropertyChanged, AddressOf item_PropertyChanged
        Next
        For Each i as ItemDetails in e.OldItems
            RemoveHandler i.PropertyChanged, AddressOf item_PropertyChanged
        Next
    End Sub

    Private Sub item_PropertyChanged(sender As Object, e As PropertyChangedEventArgs)
        'Do work
    End Sub
End Class