Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transfer data between two ViewModels

Tags:

mvvm

wpf

I have two Views and two ViewModels in my WPF app. I am using MVVM ViewModelLocator to transfer data to and fro between my ViewModels. Is this the recommended practice? Is there a better way to achieve this? I am currently using this code to access properties of ViewModel2 in ViewModel1

var _viewmodel2 = (Application.Current.Resources["Locator"] as ViewModelLocator).ViewModel2;

Thanks

like image 716
azmuhak Avatar asked Aug 05 '26 10:08

azmuhak


1 Answers

What you are after is something like the Event Aggregator pattern. It will use a central 'aggregator' object and subscribing/raising events (with payloads) to ferry data back and forth. Yes, a bit complicated. If your scenario is complex enough for this , here is some more information from a previous SO post here

However......If your scenario is less complicated, you are ok maintaining a reference in viewmodel A to viewmodel B and vice versa. Which seems like it is what you are doing with the ViewModelLocator (which actually uses DI behind the scenes to resolve the instance of ViewModel you are after). This does not violate the MVVM pattern. You just want to be sure to clean up after yourself if during the course of your data share you are subscribing to any events across the viewmodels (same case with event aggregator solution).

like image 164
Tom Florkiewicz Avatar answered Aug 07 '26 19:08

Tom Florkiewicz