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:
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With