In MVVM, ViewModel is an application. This means that I usually have one start ViewModel to start, which is the entry point to my application, and I usually 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(); }
From time to time I have an application that will create a ViewModel in the constructor of the launch window, but this is not very preferable, because it means that if I have the startup logic, I have to put this in the code. Look also, 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 this, keep in mind that when using MVVM, your ViewModels are your application, not your views, so usually your ViewModels are somehow related to the launch ViewModel. Views are just a user-friendly way to interact with your application (ViewModels).
source share