Thursday, May 17, 2012

DependencyProperty vs. INotifyPropertyChanged

I've been developing UI components for work and I've noticed a lot of shift and use between DependencyProperty and implementing the INotifyPropertyChanged interface.  When and why do we use this? 

The simplest answer is that DependencyProperty is a lot more heavyweight than INotifyPropertyChanged.  Primarily, you'll see DependencyProperty much more useful for UI components and binding, rather than on the ViewModel.  Why is this?

Simply put, implementing INotifyPropertyChanged will not allow you to style or template your control off the bat.  While there are other ways to get around this, it's a bit more of a pain and why make your life painful when you can make it simple and easy?

DependencyProperty, on the other hand, will allow you to do just that.  If you implement a Gauge control, for example, and then have it so that a specific element on the Gauge has a certain color, you won't be able to put a global style on this with INotifyPropertyChanged.  DependencyProperty will register it immediately and you're good to go.

I think it really boils down to two cases.

  1. For UI control development and tight-coupling, use DependencyProperty.
  2. For everything else (when serialization is necessary) use INotifyPropertyChanged.
That being said, there is one caveat -- writing the DependencyProperty in a ViewModel is a hell of a lot easier and quicker for updating things.  Using the "propdp" snippet in Visual Studio makes coding them a breeze.

1 comment:

  1. INotifyPropertyChanged when used also gives you the ability to add more logic in the code of your getters and setter of your properties.

    http://www.dapfor.com/en/net-suite/net-grid/features/performance

    ReplyDelete