使用ObservableCollection订阅CollectionChanged事件

时间:2015-03-27 19:32:12

标签: .net wpf vb.net observablecollection

当我创建ObservableCollection时,如何在添加或删除项目时运行其他逻辑?

Public Property Employees As ObservableCollection(Of employee)
    Get
        If _employees Is Nothing Then
            _employees = New ObservableCollection(Of employee)
            AddHandler _employees.CollectionChanged, AddressOf OnEmployeesChanged
        End If
        Return _employees 
    End Get
    Set(ByVal value As ObservableCollection(Of employee))
        _employees = value
    End Set
End Property

Private _employees As ObservableCollection(Of employee)

Protected Sub OnEmployeesChanged()
   'addtional logic...
End Sub

当我打电话

Employees.Add

Employees.Remove

- > OnEmployeesChanged并没有被解雇,而setter也不会。

员工必须通知已更改的集合(WPF UI绑定到该集合)但我不想使用两行来触发事件

_employees.Add
RaisePropertyChanged("Employees")

如何构建属性来处理此问题?

1 个答案:

答案 0 :(得分:0)

不知道VB,但这里是c#,我相信你可以翻译它

TheList.CollectionChanged += TheList_CollectionChanged;

private void TheList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {
            foreach (string model in e.NewItems)
            {
              //do something when an item is added to the collection
            }
        }
        if (e.OldItems != null)
        {
            foreach (string model in e.OldItems)
            {
               //do something when an item is removed here
            }
        }
    }