How to send parameters between viewmodels using viewmodellocator
Asked Answered
F

2

6

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?

Flossieflossy answered 16/7, 2012 at 15:6 Comment(1)
Hi are you using any MessagingServices Like that of Galasoft or any Messaging to Communicate from ViewModel to ViewCinthiacintron
B
3

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.

Butyraldehyde answered 16/7, 2012 at 16:27 Comment(1)
Thanks, I knew a little about messaging system but your article made things simpleFlossieflossy
C
1

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.

Cinthiacintron answered 16/7, 2012 at 16:2 Comment(1)
If I understand you correctly your approach can work but it will be very difficult to manage a huge system. Could you please provide some code sample to help me understand. ThanksFlossieflossy

© 2022 - 2024 — McMap. All rights reserved.