views:

201

answers:

5

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.

A: 

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.

AlvinfromDiaspar
A: 

Are you declaring and instantiating your VM in your XAML?

If so, you cannot pass arguments to the constructor but as AlvinfromDiaspar wrote, there's nothing that prevents you from instantiating it from elsewhere (in code behind), allowing to pass parameters to its constructor

vc 74
No, it's instantiated in the "ModelViewLocator" (I'm using the MVVM Light framework).
lazo
+1  A: 

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.

Doobi
+1  A: 

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.

Chris Holmes
Upvoted for suggesting dependency injection. DI makes for a much more unit-testable application.
FMM
Thanks, dependency injection is probably the most sustainable way to go forward. I have a bit of refactoring to do once I've shopped around and decide which IoC container to use.
lazo
+1  A: 

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

Rick Ratayczak
Thanks for your response. Yes, I ended up doing something similar to what you suggest here as a short-term solution.
lazo