2
votes

I'm currently going back to designing some GUI Applications using WPF + MVVM, I now find it much easier to understand than when I first encountered it.

One question that troubles me however is the startup of the application. From my view, there are two approaches:

Start from the Main Window View, have its ViewModel be instantiated by some means which again instantiates the Model it represents. This puts the View / GUI in the "operating" position.

The other way would be to override the OnStartup routine in the Application class (John Smith does it this way in his The MVVM-Design Pattern MSDN Article) and start by creating the model, passing it to the ViewModel Contructor and assign the newly created ViewModel to the DataContext of a separately created View / Window.

Is either way fine (in this case, what may be reasons to prefer one over the other) or is one violating MVVM rules?

1
I wrote a blog post answering some of your questions from my view point: blog.rsuter.com/… - Rico Suter

1 Answers

2
votes

Your first approach is correct:

Start from the Main Window View, have its ViewModel be instantiated by some means which again instantiates the Model it represents. This puts the View / GUI in the "operating" position.

The viewmodel then becomes the DC for the View. There should be a 1:1 of View to ViewModel.

You want each class to be able to be instantiated with as few dependencies as possible.

My ViewModel ctors really only consist of an argument for passing a class containing View-Specific callbacks, based on an interface.

    Model m = null;
    IViewCallbacks cb;
    public MainViewModel(IViewCallbacks mainViewCallbacks)
    {
         this.cb = mainViewCallbacks;
         m = new Model();
    }

The ViewModel instance has instances of the model(s) that I need to be able to access. The vm backing the view should be the in charge of instantiating these, otherwise your unit testing is going to suffer because of external dependencies (that instance of the model that you need to pass in via the ctor).