Best place to create a ViewModel in MVVM
In MVVM, the ViewModel is the application. This means that I usually have an single startup ViewModel that is the entry point to my application, and I typically create an instance of this in the App.xaml.cs OnStartup
code
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var app = new ShellView();
var context = new ShellViewModel();
app.DataContext = context;
app.Show();
}
Every once in a while I have an application that will create the ViewModel in the startup window's constructor, but this is not really preferred because it means if I have any startup logic, I have to put that in the code-behind the View as well, and I don't like mixing application logic in my View layer.
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ShellViewModel();
}
}
Regardless of how you do it, keep in mind that when using MVVM, your ViewModels are your application, not your Views, so typically your ViewModels are connected in some way to the startup ViewModel. Views are just a user-friendly way for users to interact with your application (the ViewModels).
There are different ways to do it, depends on what you think.
I personally always have a class designed to create all the objects I need, called in the App.xaml.cs
.
The class basically does those time-consuming startup procedures while a splashscreen is displayed. I create both Views and ViewModels here AND link them
This allows me to have one and only one point in which all those links View-to-ViewModel are created, I can come back to it easily, even if I add/remove something.
I don't like the approach in which you initialize the viewModel in each view's constructor. Assuming you have 15 views in your project, you'd have 15 different files to browse if you want to check all the ViewModel initializations.
This is my humble participation to this =)