Reputation: 974
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
Upvotes: 3
Views: 2908
Reputation: 366
If you register your viewmodels in a service locator or IoC container, you can simply fetch the reference from there.
SimpleIoc.Default.GetInstance<MyViewModel>()
Above example uses MvvmLight
Upvotes: 0
Reputation: 642
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).
Upvotes: 3