简体   繁体   中英

How do I navigate from a ViewModel?

I am writing a small contrived WPF application for a university project, and i'm taking the opportunity to learn the MVVM pattern. I've implemented my initial start up window which will be a login page.

I have bound the login button to a command that I have derived from ICommand, which is injected with the LoginViewModel. The LoginViewModel then validates the customer through a WCF service I have created.

My question is, once the viewmodel receives notification that the validation is correct, how should I navigate to the next page/window from the viewmodel? I don't want to create an instance of a new window within the viewmodel. Should I be using pages here instead? I'm keen to understand the best practices from the start, I don't want to be wasting my time learning the bad ways of doing this.

Thanks.

Instead of changing views, you can change viewmodels and use a ContentControl to bind the viewmodels to specific views: create a main view on top of the other views which will manage the view changes via commands (in this example set the CurrentViewModel from your command handler):

    <UserControl.Resources>
        <DataTemplate DataType="{x:Type vm:LoginViewModel}">
            <local:LoginView/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:FirstPageViewModel}">
            <local:FirstPageView/>
        </DataTemplate>
    </UserControl.Resources>
    <ContentControl Content="{Binding Path=CurrentViewModel}" />

This way you don't need to mix up the Views and ViewModels, you're not creating views from the VMs. Actually in my case it was the child page which requested the view change with an event.

I've not done pages, but for your login screen I would have my LoginViewModel expose a LoggedInEvent .

You can then have a parent ViewModel create the LoginViewModel and destroy it again when the LoggedInEvent is raised (and create whatever new views you need).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM