Quintic
WPF, MVVM, App Start-up

App Start-up with MVVM

One topic that sparks a great deal of discussion is how, on Application start-up should you associate the initial ViewModel and View when using the MVVM paradigm.

So, a few ground rules. You do not have to use MVVM to use WPF or UI development. It is a great paradigm to use, especially if you are working on a Project in team and/or in an enterprise application where long term maintenance and expected updates are anticipated.

Howver if you are producing a one-off quick app to achieve a specific task, then I would say don’t sweat about it. Use code behind if that gets the job done quicker and easier.

I have come across three scenarios for implementing MVVM with WPF and startup:

  • Use the View to automagically create the ViewModel and assign it as the DataContext.
  • Create the View and ViewModel at App startup and create the linkage then.
  • Use Dependency Injection to create the ViewModel and it then create the View

Automagically create the ViewModel

Under this scenario you use XAML to instanciate the ViewModel and either refernce it as the DataContext of the View, or write a couple of lines of code behind to make the ViewModel available to the rest of the application, eg:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SampleApplication"
    xmlns:mvs="clr-namespace:ViewModels"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
   <mvs:EmployeeViewModel/>
</Window.DataContext>
public partial class MainPage : UserControl
{
    public EmployeeViewModel EmployeeViewModel
    get { return this.DataContext; }
}

Must admit this is my least favourite method. I do not believe it is the responsibility of the View to create the ViewModel. Plusyou aften need to inject context into the ViewModel, and this mechansim does not provide a clean way of doing that.

Author: Daddy Raccoon