INotifyCollectionChanged 用法简介

发布时间 2023-12-17 10:22:30作者: JohnYang819

INotifyCollectionChanged 接口是 System.Collections.Specialized 命名空间中的一个接口,用于在集合发生更改时通知订阅者。这个接口通常在实现了集合的类中使用,以便在集合变化时通知监听者(如 UI 控件)进行更新。

以下是 INotifyCollectionChanged 的关键成员:

CollectionChanged 事件: 当集合发生变化时触发的事件。这个事件包含一个 NotifyCollectionChangedEventArgs 参数,该参数提供了有关集合变化的详细信息,如变化的类型(添加、移除、替换等)、受影响的索引和元素。

NotifyCollectionChangedEventArgs 类: 包含有关集合变化的详细信息的类。常见的属性包括:

Action:表示变化的类型,是一个 NotifyCollectionChangedAction 枚举值,包括 Add、Remove、Replace、Move 和 Reset。
NewItems:在 Add、Replace 和 Move 操作中,表示添加或替换的新元素的集合。
OldItems:在 Remove、Replace 和 Move 操作中,表示移除或替换的旧元素的集合。
NewStartingIndex 和 OldStartingIndex:在 Move 操作中,表示移动操作的起始索引。

using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

public class ExampleCollection : ObservableCollection<string>
{
    public ExampleCollection()
    {
        this.CollectionChanged += OnCollectionChanged;
    }

    private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        Console.WriteLine($"Collection changed: {e.Action}");

        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                Console.WriteLine($"Added item(s): {string.Join(", ", e.NewItems)}");
                break;

            case NotifyCollectionChangedAction.Remove:
                Console.WriteLine($"Removed item(s): {string.Join(", ", e.OldItems)}");
                break;

            case NotifyCollectionChangedAction.Replace:
                Console.WriteLine($"Replaced item(s): {string.Join(", ", e.NewItems)}");
                break;

            case NotifyCollectionChangedAction.Move:
                Console.WriteLine($"Moved item(s) from index {e.OldStartingIndex} to {e.NewStartingIndex}");
                break;

            case NotifyCollectionChangedAction.Reset:
                Console.WriteLine("Collection was reset");
                break;
        }
    }
}

class Program
{
    static void Main()
    {
        ExampleCollection collection = new ExampleCollection();

        collection.Add("Item 1");
        collection.Add("Item 2");

        collection.Remove("Item 1");

        collection[0] = "New Item 1";
    }
}