When implementing the ViewModel in a Model-View-ViewModel architecture WPF application there seem to be two major choices how to make it databindable. I have seen implementations that use DependencyProperty
for properties the View is going to bind against and I have seen the ViewModel implementing INotifyPropertyChanged
instead.
My question is when should I prefer one over the other? Are there any performance differences? Is it really a good idea to give the ViewModel dependencies to WPF? What else do I need to consider when make the design decision?
INotifyPropertyChanged
when used also gives you the ability to add more logic in the code of your getters and setter of your properties.DependencyProperty
example:In your getter and setter --- all you can do is simply call SetValue and GetValue respectively, b/c in other parts of the framework the getter/setter is not called, instead it directly calls SetValue, GetValue, so your property logic wouldnt reliably be executed.
With
INotifyPropertyChanged
, define an event:And then simply have any logic anywhere in your code, then call:
This could be in a getter/setter, or anywhere else.
From an expressiveness standpoint, I thoroughly enjoy using dependency properties and cringe at the thought of
INotifyPropertyChanged
. Apart from thestring
property names and possible memory leaks due to event subscription,INotifyPropertyChanged
is a much more explicit mechanism.Dependency properties imply "when this, do that" using easily-understood static metadata. It is a declarative approach that gets my vote for elegance.