集合(9-可观察的集合 ObservableCollection)

特征

何为可观察的集合?
如果需要集合元素添加和删除的信息,就可以使用ObservableCollection,这个类在WindowsBase程序集定义,这个类是为WPF定义的,如集合发生变化能通知到UI

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace ConsoleApplication34
{
    class Program
    {
        static void Main(string[] args)
        {
            ObservableCollection<string> obc = new ObservableCollection<string>();
            obc.CollectionChanged+=obc_CollectionChanged;
            obc.Add("One");
            obc.Add("Two");
            obc.Insert(1,"Three");
            obc.Remove("Three");
        }
        public static void obc_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            Console.WriteLine("action:{0}",e.Action.ToString());
            if (e.OldItems!=null)
            {
                Console.WriteLine("starting index for old item(s):{0}",e.OldStartingIndex);
                Console.WriteLine("old item(s):");
                foreach (var item in e.OldItems)
                {
                    Console.WriteLine(item);
                }
            }
            if (e.NewItems != null)
            {
                Console.WriteLine("starting index for new item(s):{0}", e.NewStartingIndex);
                Console.WriteLine("new item(s):");
                foreach (var item in e.NewItems)
                {
                    Console.WriteLine(item);
                }
            }
            Console.WriteLine();
        }
    }
}

输出如图:
这里写图片描述

示例剖析

  • 对obc加入CollectionChanged事件obc_CollectionChanged
  • 事件属于NotifyCollectionChangedEventHandler的委托类型
  • 该委托声明格式为
public delegate void NotifyCollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e);
  • 根据格式定义方法obc_CollectionChanged
  • NotifyCollectionChangedEventArgs 事件参数如图
    这里写图片描述
  • 参数e中Action属性是一个枚举类型NotifyCollectionChangedAction
    这里写图片描述
  • 查看各个属性的注释得知,OldItems 获取受 Replace、Remove或 Move 操作影响的各项的列表。
  • 其它不 一 一列举
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值