I’m prototyping a WPF application making use of the MVVM pattern. The application shall have two windows: MainWindow and LoginWindow.
The Model contains two properties: Username and Password.
The LoginWindow is responsible for handling the username and password entered by the user, so the corresponding view model updates these properties. However, the MainWindow also needs access to the username and password for later usage with a client object.
How should I handle this?
Passing the instance of the Model created in the LoginViewModel to the MainWindowViewModel‘s constructor?
What you need is a Messenger/Event Aggregator. An event aggregator is a broker object that you can take a reference to and specify what type of events you want to receive, without having to take a reference or even be aware of the objects generating the events.
Prism’s EventAggregator is the most common one. See: Event Aggregator
So:
ViewModel 1:
ViewModel 2:
What’s happening is that the eventaggregator is passed to both the viewmodels. ViewModel1 publishes a message but doesn’t know who (if anyone) is listening to it. ViewModel2 has subscribed to the event and is listening for a publisher to send it a message.
Using this approach you can have your viewmodels communicate without them taking references out on each other.