I have a question: Where is the best place to create the ViewModel in MVVM and how?
1) Create once in App.xaml.cs as static field and then use it through App?
2) Alway create new ViewModel in Page.cs, when I navigate to this page?
3) other options
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With