Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass parameter to ViewModel's constructor in a WPF application?

Tags:

c#

mvvm

wpf

prism

I see people suggests using Messenger/EventAggregator to pass parameter to ViewModel when "current" target is changed, but it doesn't work on my case.

Say I have a ViewModel class like this:

class CustomerViewModel
{
    CustomerViewModel(int customerId) {}
}

And:

  1. I have views of same type in the application shell at the same time.
  2. For each view, there is a unique CustomerViewModel instance for it. Each CustomerViewModel instance can have different customerId. (which is similar to Visual Studio IDE, multiple document opened at the same time)

I don't want to write code like "this.DataContext = new CustomerViewModel(id)" in my View class. What's the MVVM way to handle such case?

Thanks.

like image 287
Chen Avatar asked Oct 28 '12 07:10

Chen


1 Answers

There are a few ways to handle this case, first - decide if you're using a View first or View Model first approach.

Using the EventAggregator is a valid option.

Another option is to have your ViewModel implement an interface and then use some IoC/DI such as MEF or Unity to get the instance of the ViewModel. Using this method, you can define an Initalize(int Id) function which you know the ViewModel must implement. You don't need your View to know the CustomerViewModel class, only the interface.

I should note that if you are using some kind of DI, you can always inject that parameter to the ViewModel. IIRC in Unity this can be done a bit easier then in MEF (you simply register the value and then create the ViewModel which depends on that type).

like image 186
Blachshma Avatar answered Nov 10 '22 13:11

Blachshma