9.6. Observing Additions and Modifications to Dictionaries
Problem
You have multiple objects that need to observe modifications to objects that implement IDictionary<K,V>
. When an item is added or modified in the dictionary-based collection, each of these observer objects should be able to vote to allow or disallow the action. In order for an action to be allowed to complete, all observer objects must state if they are vetoing the action. If even one observer object votes to disallow the action, the action is prevented.
Solution
Use the ObservableDictionaryObserver
class implemented in Example 9-5 to observe additions and modifications to the ObservableDictionary
class (shown in Example 9-4) object that is registered with this object. The ObservableDictionary
class is a generic wrapper for collections that implement IDictionary<K,V>
and allows itself to be observed by the ObservableDictionaryObserver
class.
The ObservableDictionaryEventArgs
class is a specialization of the EventArgs
class, which provides the IDictionary<K,V>
key and value being added or modified to the ObservableDictionaryObserver
object, as well as a Boolean property, KeepChanges
. This flag indicates whether the addition or modification in the ObservableDictionary
object will succeed or be rolled back. The MakeObservableDictionary
extension method for IDictionary<K,V>
wraps up the code for creating an ObservableDictionary
from an IDictionary
instance. Example 9-4 illustrates the two classes and the extension method. ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.