添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
  • Task Parallel Library
  • Back to basics: algorithms, data structures, interview questions
  • Emailing
  • Globalization
  • Generics
  • Reflection
  • Diagnostics
  • String operations
  • File I/O
  • Other technologies
  • Node.js
  • Amazon cloud/Big Data
  • Python
  • JavaScript
  • GitHub
  • About
  • Contact
  • Imagine that you’d like to be notified when something is changed in a collection, e.g. an item is added or removed. One possible solution is to use the built-in .NET generic collection type ObservableCollection of T which is located in the System.Collections.ObjectModel namespace. The ObservableCollection object has an event called CollectionChanged. You can hook up an event handler to be notified of the changes.

    If you don’t know what events, event handlers and delegates mean then start here .

    Let’s see a simple example with a collection of strings:

    ObservableCollection<string> names = new ObservableCollection<string>(); names.Add("Adam"); names.Add("Eve"); names.Add("Clive"); names.Add("Anne"); names.Add("John"); names.Add("Peter"); names.Add("Hannah");

    Nothing special so far I guess. This looks exactly like a “normal” collection.

    The following example demonstrates the CollectionChanged event:

    private static void RunObservableCollectionCode() ObservableCollection<string> names = new ObservableCollection<string>(); names.CollectionChanged += names_CollectionChanged; names.Add("Adam"); names.Add("Eve"); names.Remove("Adam"); names.Add("John"); names.Add("Peter"); names.Clear(); static void names_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) Debug.WriteLine("Change type: " + e.Action); if (e.NewItems != null) Debug.WriteLine("Items added: "); foreach (var item in e.NewItems) Debug.WriteLine(item); if (e.OldItems != null) Debug.WriteLine("Items removed: "); foreach (var item in e.OldItems) Debug.WriteLine(item);

    The NotifyCollectionChangedEventArgs object resides in the System.Collections.Specialized namespace.

    If I run the RunObservableCollectionCode method I get the following output:

    Change type: Add
    Items added:
    Change type: Add
    Items added:
    Change type: Remove
    Items removed:
    Change type: Add
    Items added:
    Change type: Add
    Items added:
    Peter
    Change type: Reset

    You can then decide how to handle additions and deletions in the event handler.

    View all various C# language feature related posts here .

    Advertisement

    History

    Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
    To find out more, including how to control cookies, see here: Cookie Policy