I’m making a WPF application making use of the MVVM light framework.
What I’m trying to do is have a login form in a view, when the user presses a button within that view it launches a LoginCommand for the attached ViewModel. From there I either want to launch a new window which holds the rest of the application, or simply switch views from the same window.
Currently I have it so that there is a view called MainView which has a content control inside bound to View1. However to switch to View2 I need to put the button for this on MainView, and not within View1 where it belongs.
Any advice?
Usually I do this one of two ways:
If the login window is a one-time thing required before starting the application, I will put it in the
OnStartup()method of theApplicationobjectThe other way I usually do this is through a
ShellViewModelorApplicationViewModelwhich handles all my window management. This method usesDataTemplatesto define each screen, and uses aContentControlas a placeholder for the current screen in theShellVieworApplicationView.I usually combine this with an Event System of some kind, like Microsoft Prism’s
EventAggregator, so it can listen for messages of a specific type, such asOpenWindoworCloseWindowmessages. If you’re interested, I have a blog post about Communication between ViewModels that should give you a better idea of what an event system looks like.For example, my
ShellViewModelmight start by displaying aLoginViewModel(aDataTemplateis used to tell WPF to draw theLoginViewModelwith theLoginView), and it would subscribe to receive messages of typeSuccessfulLogin. Once theLoginViewModelbroadcasts aSuccessfulLoginmessage, theShellViewModelwill close theLoginViewModeland replace it with theApplicationViewModel. You can see an example of this in my article on Navigation with MVVM