Communicating property changes

D

David Veeneman

This posting is for the Google crawler and requires no response.

I have created a multi-level object hierarchy, in which the root object
needs to be notified whenever any property of any object in the collection
changes. I wanted to enable this communication without passing child objects
references to their parents. Those references increase the internal coupling
of an object hierarchy and should be avoided where possible.

Here is how I solved the problem:

Each item (non-collection) class in the hierarchy implements the
INotifyPropertyChanged interface--it fires a PropertyChanged event when any
property in the object changes.

All collection classes in the hierarchy derive from the BindingList<T> base
class, which means they implement the IBindingList interface. As a result,
they listen for property changes in the objects they contain, so long as
those objects implement the INotifyPropertyChanged interface. The collection
fires a ListChanged event when it receives a PropertyChanged event from one
of its objects.

Each item class in the hierarchy that has a collection as one of its
properties subscribes to the ListChanged event of that collection. For all
items other than the root object of the hierarchy, the item's event handler
fires a PropertyChanged event for the collection property. The root object's
event handler does the actual processing.

This is how it works: Assume a KnowledgeBase object that contains a
Categories collection property. Each Category object in that collection
contains an Articles collection. Each Article object in that collection
contains several properties, including a Text property.

Now, let's say an Article's text is changed.

-- The Article object fires a PropertyChanged event for the Text property.

-- The Articles collection receives the event and fires a ListChanged event.

-- The Category object to which the Articles collection belongs receives
that event and fires a PropertyChanged event for the Articles property.

-- The Categories collection receives the event and fires its ListChanged
event.

-- The KnowledgeBase object receives the event and processes it.

The result is that the KnowledgeBase object is notified of any changes to
any object in the hierarchy. This behavior is very useful for setting
'IsDirty' flags and the like. Note that this solution, as written, only
works under .NET 2.0.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top