Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send parameters between viewmodels using viewmodellocator

I am creating a WPF application using MVVMLight. I use ViewModelLocator to create viewmodels. My problem is passing parameters between them.

For example we have a situation:

We have a grid with some entities, when one of them is doubleclicked I need to create a new view with details of that entity. How to send the selected item id to ViewModel of the new View?

like image 474
Eugene Avatar asked Jul 16 '12 15:07

Eugene


2 Answers

Typically you would use some kind of messaging system, such as Prism's EventAggregator or MVVM Light's Messenger.

Both systems remind me of a paging system: any part of the application can broadcast messages, and any part of the application and subscribe to listen for messages.

So your DoubleClick command would broadcast a LoadItemMessage containing the selected item Id, and whatever is responsible for showing the item would subscribe to receive LoadItemMessages and would load the item whenever it hears a LoadItemMessage.

If you're interested, I have a brief article on my blog about Communication between Viewmodels with MVVM that gives a high level overview of event systems.

like image 178
Rachel Avatar answered Oct 14 '22 02:10

Rachel


That is a problem with ViewModelLocator (to pass the parameters to ViewModel from View xaml). What you can do is Create a Property Parameter of Type object or (of type your SelectedItem) in ViewModelLocator class. Bind this to the SelectedItem of your Grid and then pass it to your new ViewModel. I hope this will help. NOte: If you create the property of type object don't forget to cast it.

like image 29
yo chauhan Avatar answered Oct 14 '22 01:10

yo chauhan