IdentityMine

| Tags: WPF

originally posted by Josh Smith: (link) - please comment at original post

EDIT: Shortly after publishing this blog post, I received some excellent feedback on it, and updated the PropertyObserver class to implement IWeakEventListener.  Special thanks go to Huseyin Tufekcilerli for posting an IWeakEventListener implementation, which got me 90% of the way toward a better solution. This blog post and its source code download have been updated to reflect this improvement.

When working with objects that implement INotifyPropertyChanged, as most ViewModel objects tend to do, it often becomes necessary to attach a handler to their PropertyChanged event.  Your code can quickly accumulate many event handling methods full of conditional statements that check if e.PropertyName equals some hard-coded string value.  This leads to messy, brittle code that becomes difficult to maintain as the mess gets larger.

To combat this evil, I decided to mechanize as much of this as possible.  I created a generic class called PropertyObserver<TPropertySource> which monitors the PropertyChanged event of an object, and executes whatever callback methods you have registered for when certain properties have changed.  In addition, that class will verify that every property name you register with it is a real, public property on the object being observed, because the way that you provide the property  name is checked by the compiler (you pass it a lambda expression that references the property).  If a property name changes, but you forgot to update your code that registers the property with PropertyObserver, you will get a compiler error next time you try to build your solution.

Here are the two methods of interest:

01_js071309

Here is a simple example, from the source code download, that shows how to use PropertyObserver:

02_js071309

You can download the source code here.  Note: Change the file extension from .DOC to .ZIP and then decompress it.

Remember to please comment at original post: (link)

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on TumblrEmail this to someoneDigg thisFlattr the authorShare on StumbleUpon

Comments are closed.