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 theApplication
objectThe other way I usually do this is through a
ShellViewModel
orApplicationViewModel
which handles all my window management. This method usesDataTemplates
to define each screen, and uses aContentControl
as a placeholder for the current screen in theShellView
orApplicationView
.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 asOpenWindow
orCloseWindow
messages. 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
ShellViewModel
might start by displaying aLoginViewModel
(aDataTemplate
is used to tell WPF to draw theLoginViewModel
with theLoginView
), and it would subscribe to receive messages of typeSuccessfulLogin
. Once theLoginViewModel
broadcasts aSuccessfulLogin
message, theShellViewModel
will close theLoginViewModel
and replace it with theApplicationViewModel
. You can see an example of this in my article on Navigation with MVVMPut your views inside
Page
elements, inside yourMainWindow
create a Frame and point it's source to your first page.From then on you can use the frame's
NavigationService
to navigate your frame to another view, much like a web browser.