views:

9234

answers:

11

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?

+7  A: 

The choice is totally based on your business logic and UI abstraction level. If you dont want a good separation then DP will work for you.

DependencyProperties will be applicable mainly at the VisualElements level so it won't be good idea if we create lot of DPs for each of our business requirements. Also there is a greater cost for DP than a INotifyPropertyChanged. When you design a WPF/Silverlight try to design UI and ViewModel totally separate so that at any point of time we can change the Layout and UI controls (Based on theme and Styles)

Refer this post also - http://stackoverflow.com/questions/275098/what-applications-could-i-study-to-understand-datamodel-view-viewmodel . The link has a lot of reference to Model-View-ViewModel pattern, which is very relevant to this discussion.

Jobi Joy
The post by jbe answers the differences more accurately. Just because a VM (or Presenter) inherits from DependencyObject doesn't mean that it can't be styled or isn't logically separate from the View, it just means that the storage for the property values is different than explicitly declared fields in the POCO style.That being said, serialization, logical equality, and thread affinity are real issues which DepedencyObject-based VMs have to deal with.
micahtan
I second micahtan opinion on jbe answer.
Sergey Aldoukhov
+2  A: 

Is it really a good idea to give the ViewModel dependencies to WPF?

.NET 4.0 will have System.Xaml.dll, so you won't have to take a dependency on an arbitrary framework to utilize it. See Rob Relyea's post about his PDC session.

My take

XAML is a language for describing objects, and WPF is a framework whose described objects are UI elements.

Their relationship is similar to C#, a language for describing logic, and .NET, a framework which implements particular kinds of logic.

XAML's purpose is declarative object graphs. The W*F technologies are great candidates for this paradigm, but XAML exists independently of them.

XAML and the entire dependency system were implemented as separate stacks for WF and WPF, probably to leverage the experience of different teams without creating a dependency (no pun intended) between them.

Bryan Watts
A: 

So the main reason to stay away frm DP is performance? Are there also advantages of DP over INotifyPropertyChanged? What can I do with DPs what I can't with INotifyPropertyChanged. In both cases two way databindng seems to work.

bitbonk
For future reference this would be better as a comment on the post(s) you're replying to.
Bryan Anderson
I added an answer that partially answers this specific question
Adam
Actually, DependencyProperties are the solution with greater performance. Comparison's I've seen show them as less memory and CPU overhead from binding and non-binding scenarios. In addition, they are sparse (no additional memory for instances with default values).There may be some other aspects in which INotifyPropertyChanged has a performance advantage, but I don't know of it and I think the above two cases cover the most common use cases.
nedruod
+4  A: 

From an expressiveness standpoint, I thoroughly enjoy using dependency properties and cringe at the thought of INotifyPropertyChanged. Apart from the string 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.

Bryan Watts
+1  A: 

I too had to consider this decision recently.

I found that the INotifyPropertyChanged mechanism suited my needs better because it allowed me to glue my GUI to an existing business logic framework without duplicating state. The framework I was using had its own observer pattern and it was easy to forward one level of notification on to the next. I simply had a class which implemented the observer interface from my business logic framework and the INotifyPropertyChanged interface.

With DP you cannot define the backend that stores the state yourself. I would have had to let .net cache a copy of every item of state I was binding to. This seemed like an unnecessary overhead - my state is large and complicated.

So here I found INotifyPropertyChanged better for exposing properties from business logic to GUI.

That being said where I needed a custom GUI widget to expose a property and for changes to that property to affect other GUI widgets DP proved the simple solution.

So there I found DP useful for GUI to GUI notification.

morechilli
+1  A: 

I prefer a more direct approach, which I blogged about in Presentation Model Without INotifyPropertyChanged. Using an alternative to data binding, you can bind directly to CLR properties without any bookkeeping code. You just write plain-old .NET code in your View Model, and it gets updated when your Data Model changes.

Michael L Perry
+3  A: 

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:

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 called, instead it directly calls SetValue, GetValue, so your property logic wouldnt reliably be executed.

With INotifyPropertyChanged, define an event:

public event PropertyChangedEventHandler PropertyChanged;

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

// ...
// Something cool...
// ...

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

// More cool stuff that will reliably happen...

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

Adam
You can get change notifications from DependencyProperties as well. See PropertyMetadata.PropertyChangedCallback. Example at: http://msdn.microsoft.com/en-us/library/ms745795.aspx
Joe White
A: 

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.

However, your ViewModel is better off using INotifyPropertyChanged. Using INotifyPropertyChanged will give you the ability to have getter/setter logic if you need to.

I recommend checking out Josh Smith's version of a base class for a ViewModel that already implements INotifyPropertyChanged:

http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/

I think this is an excellent example of how to do a ViewModel.

timothymcgrath
+32  A: 

Kent wrote an interesting blog about this topic: View Models: POCOs versus DependencyObjects.

Short summary:

  1. DependencyObjects are not marked as serializable
  2. The DependencyObject class overrides and seals the Equals() and GetHashCode() methods
  3. A DependencyObject has thread affinity – it can only be accessed on the thread on which it was created

I prefer the POCO approach. A base class for PresentationModel (aka ViewModel) which implements INotifyPropertyChanged interface can be found here: http://compositeextensions.codeplex.com

jbe
DependencyObject also takes a dependency on the WPF libraries, whereas POCO does not, allowing your view models to drive some other UI stack where WPF isn't available (Compact Framework, Mono).
codekaizen
It's clear then, that the Dependecy Properties are solely built for the UI and not for the business layer.
Andrei Rinea
A: 

I think DependencyProperty and INotifyPropertyChanged are used for two different things in Binding : the first for enabling a property to be a target of a binding and receive the input from another property (use {Binding ...} to set the property), the last when you want the value of a property to be used as the source of a binding (name in the Binding Path Expression). So the choice is merely technical.

Domnik