Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason that there is no ObservableKeyedCollection (or any other such type which is merely a combination of other generic types) is because <a href="http://msdn.microsoft.com/en-us/library/ms668604.aspx" rel="nofollow noreferrer">ObservableCollection</a> is generic, and that makes implementation of an "ObservableKeyedCollection" as easy as this:</p> <pre><code>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; public class DictionaryWatcher : ObservableCollection&lt;KeyValuePair&lt;string, object&gt;&gt;, IDisposable { private NotifyCollectionChangedEventHandler watcher; private bool watching = false; public DictionaryWatcher() { watcher = new NotifyCollectionChangedEventHandler( ReportChange ); CollectionChanged += watcher; Watched = true; } public bool Watched { get { return watching; } set { if (watching) { lock (this) { CollectionChanged -= watcher; watching = false; } } } } public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } public void Initialize() { this.Add( new KeyValuePair&lt;string, object&gt;( "First", 1 ) ); this.Add( new KeyValuePair&lt;string, object&gt;( "Second", 2 ) ); this.Add( new KeyValuePair&lt;string, object&gt;( "Turd", 3 ) ); KeyValuePair&lt;string, object&gt; badValue = this[2]; this.Remove( badValue ); } protected virtual void Dispose( bool disposing ) { if (disposing &amp;&amp; Watched) { Watched = false; } } private void ReportChange( object sender, NotifyCollectionChangedEventArgs e ) { Console.WriteLine( "Change made: {0}", e.Action ); } } </code></pre> <p>While that is certainly not a one-liner program, most of it is boilerplate. Most importantly, it doesn't re-implement the <a href="http://msdn.microsoft.com/en-us/library/ms668604.aspx" rel="nofollow noreferrer">ObservableCollection</a> as you were suggesting; instead it fully utilizes it.</p> <p>The reason that it "whouldn't be a good addition to the .NET Framework" is because when there's already one way to do something, creating another way to do it is a bad idea. The fewer ways there are to get some particular task done, the fewer ways there are to do it poorly. 8 )</p> <p>The tools are provided, it's now all about how you use them.</p> <p>Hope that helps!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload