views:

83

answers:

2

I'm just starting to dig into the MVVM pattern for WPF but because I'm not a professional developer, I sometimes feel a little lost.

The main problem I have is deciding who should create whom: Let's say I have a database storing dogs and cats. I would then have a DatabaseManager which communicates with the database (Unit of Work!?), a DogRepository / CatRepository and the Dogs / Cats objects.

On the other side I have my MainWindow with which the user can open/close the database and which contains a Listbox for cats and one for dogs, so I need a MainWindowViewModel, CatsViewModel and DogsViewModel.

But how do I create these objects? In my application I create the MainWindow obviously. And then? Do I create a MainWindowViewModel and pass it to the MainWindow or does the MainWindow create its own MainWindowViewModel? How is the DatabaseManager created? By the MainWindowViewModel?

What about the CatsViewModel and the corresponding CatRepository? Does the MainWindowViewModel create the CatsViewModel which in turn creates a CatRepository? I'm really confused.

+1  A: 

You are confused because all of these options are valid. If you aren't using dependency injection and the ViewModels have all of the information they need on their own, there's no reason not to have the view create the viewmodel (usually done by creating one via a StaticResource for the View:

<Window.Resources>
     <local:CatViewModel x:Key="catVM" />
</Window.Resources>
<Grid DataContext="{StaticResource catVM}">
...
</Grid>

If you are using dependency injection, it's still perfectly valid to declare your VM as a dependency of your view in its constructor:

public CatView(CatViewModel vm) : this()
{
     this.DataContext = vm;
}

The last option is the concept of a third party that creates both the view and the viewmodel (however is appropriate) and marries them from outside of both. Usually this is called a presenter.

In any case, all of these are valid options. You should pick the one that is most appropriate for you. I'm sure someone will come along and claim blasphemy, but it's really up to your needs and your project.

Anderson Imes
Thanks for your explanation. It took me a while to get familiar with WPF and MVVM and now I can appreciate your answer.
CaptainProton
Glad I could help!
Anderson Imes
A: 

The View-Model-ViewModel (MVVM) pattern doesn't define who is responsible to create the different classes. Therefore, you find a lot different approaches in the MVVM community.

I like to use an Application Controller or use-case controllers that handle the work-flow of the application and so they are responsible to create the ViewModel and Repository classes.

A concrete example how this works is shown in the ViewModel sample of the project:

WPF Application Framework (WAF)

http://waf.codeplex.com

jbe