Passing a parameter to the ViewModel constructor

Is it possible to pass a parameter to the ViewModel constructor? Then I used this parameter to initialize the property and / or perform other operations in the ViewModel.

With WinForms I could do

  public MyForm (MyParamType myParam) {
     MyFormProperty = myParam;
     // etc.
 }

How do I do something like this in the MVVM / template using MVVM Light?

Any suggestions would be greatly appreciated. Thanks in advance.

+4
source share
4 answers

I would recommend using an IoC container and configure your container to supply the parameter when building.

For example, here the typical code for UserControl looks for me in WPF:

public partial class MyDataGridView : IMyListView { public MyDataGridView() { InitializeComponent(); } public MyDataGridView(MyListViewModel viewModel) { InitializeComponent(); DataContext = viewModel; } } 

StructureMap creates MyListViewModel for me because by default it searches for the most greedy constructor and then provides dependencies. In my StructureMap configuration, I can indicate that MyListViewModel will be provided with any parameters needed when building this object.

In a container like StructureMap, I don't need β€œnew” objects. Ever.

+4
source

If you use MVVM highlighting (even if you have no idea), you can register a message handler using Messenger, which takes your constructor parameters (or its tuple) and updates the virtual machine whenever you need to "restore" it.

+3
source

Since all view models are static in the locator, you can simply access these properties without changing the constructor.

+1
source

I do not understand why you cannot just create a viewmodel yourself. You can always create your own viewmodel. If there is a view model provided by MVVM Light, you can always inherit it and create an overloaded constructor.

-1
source

All Articles