Question

Is it possible to pass a parameter to the ViewModel constructor? I would then use this parameter to initialise a property and/or do other operations in the ViewModel.

With WinForms I could do

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

How do I go about doing something similar in the MVVM pattern / using MVVM Light?

Any suggestions would be most welcome. Thanks in advance.

Was it helpful?

Solution

I would recommend using an IoC container and configuring your container to supply the parameter upon construction.

For instance, here's what a typical code-behind to a UserControl looks like for me in WPF:

public partial class MyDataGridView : IMyListView
{
    public MyDataGridView()
    {
      InitializeComponent();
    }

    public MyDataGridView(MyListViewModel viewModel)
    {
      InitializeComponent();

      DataContext = viewModel;
 }
}

StructureMap creates the MyListViewModel for me because by default it searches for the greediest constructor and then provides the dependencies. In my StructureMap configuration, I can specify that the MyListViewModel be provided with whatever parameters are necessary upon construction of that object.

With a container like StructureMap, I don't have to "new" up objects. Ever.

OTHER TIPS

If you're using MVVM light (even if you're not I guess) you could register a message handler with the Messenger that takes your constructor parameters (or a tuple thereof) and updates the VM whenever you need to "reconstruct" it.

Since all the view models are static on the locator, you can just access those properties already without changing a constructor.

I dont understand why you cant just create the viewmodel yourself. You can always create your own viewmodel. If there is a viewmodel provided by MVVM Light then you can always inherit from that one and create an overloaded constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top