Subscribing to CollectionChanged event with ObservableCollection

左心房为你撑大大i 提交于 2019-12-11 09:56:15

问题


When I create an ObservableCollection, how to run additional logic when items added or removed?

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

When I call

Employees.Add

or

Employees.Remove

--> OnEmployeesChanged doesn't get fired and setter won't either.

Employees must notify the collection changed (WPF UI binding to that) but I don't want to use two lines to fire the event

_employees.Add
RaisePropertyChanged("Employees")

How should the property be structured to handle this?


回答1:


Don't know VB, but here it is in c#, i'm sure you can translate it

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
            }
        }
    }


来源:https://stackoverflow.com/questions/29308781/subscribing-to-collectionchanged-event-with-observablecollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!