Choosing DependencyProperty or INotifyPropertyChanged in WPF

Dependency properties are NOT intended to support source to data binding, this is where INotifyProperty comes in. From a pure point of view you shouldn’t use DP on a ViewModels. INotifyPropertyChanged better for exposing properties from business logic(viewmodel) to GUI(view).

It seems that Dependency Properties should be used in controls that you create such as Buttons. To use properties in XAML and use all the WPF features, those properties must Dependency Properties.

INotifyPropertyChanged gives you the ability to add more logic in the code of your getters and setter of your properties.
INotifyPropertyChanged Example:

With INotifyPropertyChanged, define an event:
public event PropertyChangedEventHandler PropertyChanged;

And then simply have any logic anywhere in your code, then call:

if( this.PropertyChanged != null )
{
PropertyChanged( this, new PropertyChangedEventArgs( “Name” ) );
}

// …… This could be in a getter/setter, or anywhere else.

DependencyProperty example:

public static DependencyProperty NameProperty = DependencyProperty.Register( “Name”, typeof( String), typeof( Customer ) );

public String Name
{
set { SetValue( NameProperty, value ); }
get { return ( String ) GetValue( NameProperty ); }
}
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.

Short summary:

1. DependencyObjects are not marked as serializable
2. A DependencyObject has thread affinity – it can only be accessed on the thread on which it was created.
3. As far as I know, DependencyProperty is only required when you need

PropertyValue inheritence
you need to allow the property to be set in Style setters
Use animation for the property

References:

http://kentb.blogspot.in/2009/03/view-models-pocos-versus.html

http://stevenhollidge.blogspot.in/2011/05/dependency-objects-vs.html

http://www.codeproject.com/Articles/62158/DependencyProperties-or-INotifyPropertyChanged

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s