Best place to create ViewModel in MVVM

My question is: where is the best way to create a ViewModel in MVVM and how?

1) Create once in App.xaml.cs as a static field, and then use it through the App?

2) Always create a new ViewModel in Page.cs when I go to this page?

3) other parameters

+4
source share
3 answers

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).

+9
source

You can use dependency injection and create it like this (if you use any DI container):

  public partial class YourView : UserControl { public YourView (IYourViewModel viewModel) { InitializeComponent(); this.DataContext = viewModel; } } 
+1
source

There are different ways to do this, depending on what you think.

I personally always have a class designed to create all the objects I need, called in App.xaml.cs The class basically performs these time-consuming startup procedures while the splash screen is displayed. I create both views and ViewModels here and link them

This allows me to have one and only one point at which all these View-to-ViewModel links are created, I can easily return to it even if I add / remove something.

I don't like the approach in which you initialize the viewModel in each view constructor. Assuming you have 15 views in your project, you will have 15 different files to view if you want to check all the initializations of the ViewModel.

This is my modest participation in this =)

+1
source

Source: https://habr.com/ru/post/1435124/


All Articles