C# 关于当ObservableCollection增删查改元素时,触发事件用例

ObservableCollection 类提供了一种实时监测集合变化的机制,可以通过订阅 CollectionChanged 事件来响应集合的添加、移除和重置等变化。

csharp 复制代码
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

class Program
{
    static void Main()
    {
        ObservableCollection<string> collection = new ObservableCollection<string>();

        // 订阅 CollectionChanged 事件
        collection.CollectionChanged += Collection_CollectionChanged;

        // 向集合中添加元素
        collection.Add("item 1");
        collection.Add("item 2");
        collection.Add("item 3");

        // 从集合中移除元素
        collection.Remove("item 2");

        // 清空集合
        collection.Clear();
    }

    static void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            Console.WriteLine("元素已添加:");

            foreach (string item in e.NewItems)
            {
                Console.WriteLine(item);
            }
        }
        else if (e.Action == NotifyCollectionChangedAction.Remove)
        {
            Console.WriteLine("元素已移除:");

            foreach (string item in e.OldItems)
            {
                Console.WriteLine(item);
            }
        }
        else if (e.Action == NotifyCollectionChangedAction.Reset)
        {
            Console.WriteLine("集合已重置");
        }
    }
}

Tips

在 ObservableCollection 中,如果你更改了集合中的元素,例如修改了元素的属性,这将会触发 CollectionChanged 事件。

但是如果你只是替换了集合中的元素(即通过索引直接赋值),这将不会触发 CollectionChanged 事件

相关推荐
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说2 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔2 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机