【问题标题】:INotifyPropertyChanged within child bindinglists [closed]子绑定列表中的 INotifyPropertyChanged [关闭]
【发布时间】:2017-07-10 17:34:03
【问题描述】:

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

如果我将某些东西绑定到父类,它会正确地反映对父类属性的更改 - 对以下内容的更改除外:

  1. BindingList(of ChildClass) 中的元素数量[由于添加或删除列表中的项目]。或
  2. BindingList(of ChildClass) 中项目的属性发生变化

如果我将某些内容直接绑定到 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

【问题讨论】:

  • 请给我们一些代码。

标签: c# .net vb.net inotifypropertychanged bindinglist


【解决方案1】:

BindingList&lt;T&gt; 提供事件BindingList&lt;T&gt;.ListChanged

在列表或列表中的项目更改时发生。

您可以轻松地在父类中实现事件处理程序并将其连接到ListChanged。 (我假设 children 属性 - BindingList&lt;ChildClass&gt; - 被命名为 Children

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

使用OnPropertyChanged,您可以通知订阅者Children属性已更改。如果你的类中还没有实现,它可能如下所示

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

其中[CallerMemberName](位于System.Runtime.CompilerServices 命名空间中)提示编译器在未传递显式值的情况下使用已调用OnPropertyChanged 的属性的名称。

【讨论】:

  • 现象级的。只是简单的作品。谢谢。
  • 很高兴我能帮上忙 :)
猜你喜欢
  • 2012-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 2018-08-31
相关资源
最近更新 更多