子绑定列表中的 INotifyPropertyChanged

INotifyPropertyChanged within child bindinglists

我有一个父 class(实现 INotifyPropertyChanged),它有一个 属性,它是 (ChildClass) 的绑定列表。 ChildClass 还实现了 INotifyPropertyChanged.

如果我将某些内容绑定到父项class,它会正确反映对父项class 属性的更改 - 除了对以下内容的更改:

  1. BindingList(of ChildClass) 中的元素数 [作为在列表中添加或删除项目的结果]。或者
  2. BindingList(of ChildClass)
  3. 中某项的 属性 更改

如果我将某些东西直接绑定到 ChildClass 的项目(即 BindingList(Of ChildClass) 中的项目)- 也可以。

如何连接它以便#1 和#2 适当地反映在绑定对象中?

这是 Paul 出色回答的 vb 版本。如果没有 List_Changed 事件,对 BindingList 的更改不会在嵌套业务对象中正确传播到链中。有了它,他们就是!

Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private WithEvents m_children As IBindingList

Public Sub NotifyPropertyChanged(<CallerMemberName()> Optional ByVal propertyName As String = Nothing)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub

Public Property Children As IBindingList
    Get
        Return m_children
    End Get
    Set
        m_children = Value
        NotifyPropertyChanged()
    End Set
End Property

Private Sub m_children_ListChanged(sender As Object, e As ListChangedEventArgs) Handles m_children.ListChanged
    NotifyPropertyChanged(NameOf(Children))
End Sub

BindingList<T> 提供 BindingList<T>.ListChanged 事件

Occurs when the list or an item in the list changes.

您可以轻松地在 parent class 中实现 event-handler 并将其连接到 ListChanged。 (我假设 children 属性 - BindingList<ChildClass> - 被命名为 Children

private void Children_OnListChanged(object sender, EventArgs e)
{
    OnPropertyChanged(nameof(Children));
}

使用 OnPropertyChanged 您可以通知订阅者 Children属性 已经更改。如果您的 class 中没有实现,它可能看起来像下面的

private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

其中 [CallerMemberName](位于 System.Runtime.CompilerServices 命名空间中)提示编译器使用已调用 OnPropertyChanged 的 属性 的名称,如果没有显式传递值。