I am writing a program with 4 Views: CompanyView, MembersView, WeeksView and ReportsView. Each has a corresponding ViewModel and Model. I have used PRISM BindableBase to create the ViewModels. The data binds correctly.
- CompanyViewModel contains an Object of type Company.
- MembersViewModel contains an ObservableCollection of Member Objects.
- WeeksViewModel contains an ObservableCollection of Week Objects.
Navigation is performed via top buttons in the MainWindow, with any View able to be selected at any time.
Container.RegisterTypeForNavigation<CompanyView>("CompanyView");
Container.RegisterTypeForNavigation<MembersView>("MembersView");
Container.RegisterTypeForNavigation<WeeksView>("WeeksView");
Container.RegisterTypeForNavigation<ReportsView>("ReportsView");
The problem is that WeeksViewModel must also have access to the Members ObservableCollection. And the ReportsViewModel must also have access to the Company Object, Members ObservableCollection and the Weeks ObservableCollection.
I am not sure how to implement this. How can I easily share the data between the ViewModels?
I have tried using the PRISM IEventAggregator to Publish the ObservableCollections when they are updated, and this works, however the View must first be accessed before it can listen to the Event. If the user has not clicked on "Weeks" view before, the updated MembersCollection wont reach the WeeksView. Could I pre-initialise the Views? How would I do this?
I followed the MVVM Made Simple with Prism - Webinar (https://www.youtube.com/watch?v=ZfBy2nfykqY) and discovered the same problem written in the comments. Brian Lagunas suggests the only way to fix this is via Navigation Parameters:
I have a small problem with the UpdateEvent passing the message from ViewAViewModel to ViewBViewModel. It doesn't seem to work if I have not visited ViewB, I assume this is because the ViewBViewModel has not yet been instantiated until the view for it has been loaded at least once.
Anybody got any ideas on this, I assume instantiating all viewmodels before they're needed is a bad idea, so how can you get default information into a viewmodel from other viewmodels before it's been instantiated?
Brian Lagunas: The only way to do it is to pass that information as a parameter when you navigate to ViewBViewModel.
I have considered using Navigation Parameters, but it seems you must know from WHERE to WHERE you are navigating. E.G. From MembersView > WeeksView, pass the Members Collection as a Parameter. But users can naviagate in any order, including directly to WeeksView on program load. e.g. How does the WeeksView get the Members Collection if they came from the Company View? Company does not know about Members Collection.
I am open to other ideas, I have researched far and wide and am completely stuck :-(
Thanks very much for your ideas and help! Kind Regards, Damian