vableCollection订阅CollectionChang

vableCollection订阅CollectionChang

本文介绍了用ObservableCollection订阅CollectionChanged事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当我打电话

Employees.Add

Employees.Remove

-> OnEmployeesChanged不会被解雇,setter也不会.

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

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

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")

该属性应如何处理?

推荐答案

不知道VB,但是在C#中,我确定您可以翻译它

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

这篇关于用ObservableCollection订阅CollectionChanged事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:22