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 事件

相关推荐
脚踏实地皮皮晨9 分钟前
003003002_WPF Grid 基类官方类定义逐行深度解析
开发语言·windows·算法·c#·wpf·visual studio
xieliyu.10 分钟前
Java 线程池入门详解:线程池基础定义 + ThreadPoolExecutor 全参构造方法逐参数解析
java·开发语言·idea·javaee
一条泥憨鱼12 分钟前
【从0开始学习计算机网络】| HTTP方法疑点解析
开发语言·计算机网络·http
微学AI9 小时前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
豆瓣鸡10 小时前
算法日记 - Day3
java·开发语言·算法
凯丨11 小时前
AI 蠕虫来了:恶意文档如何通过 Copilot for Word 自我传播?
人工智能·c#·copilot
韭菜炒鸡肝天11 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
Aaron - Wistron11 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
Dxy123931021612 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
05664613 小时前
Python康复训练——常用标准库
开发语言·python·学习