Question

I have a Windows Universal App which involves Login. A typical scenario with this kind of application is different states. For example whether the user is yet to login for the first time or has the user already logged in before and just reopening the app again. Depending on the state here are the actions

IfLoggedIn - Show HomePage || IfNotLoggedIn - Show LoginPage

Now based on the condition(state) we have to show different pages.

My question is similar to this but I wanted to understand how to implement the same in MVVM and what is the right place to put this conditional logic.

Putting it in app.xaml.cs will solve the problem but messes up your app.xaml.cs and violates the MVVM because ViewModel is not handling the interaction logic.

The solution that I tried is

  1. Create an intermediate Page(Intermediate.xaml).
  2. Create corresponding ViewModel(IntermediateViewModel.cs) for the above.
  3. In the constructor of this ViewModel incorporate the conditional statement to decide which page to Navigate.

Let us assume I have my condition in the bool variable IsLoggedIn. Where to put the conditional check?

The code in my IntermediateViewModel is as follows

public bool IsLoggedIn {get; set;}
//IsLoggedIn contains the condition of whether the user is logged-in or not-logged-in

public IntermediateViewModel()
{
    if (IsLoggedIn == false) 
    {
        NavigationService.Navigate("LoginPage");
    }
    else if (IsLoggedIn == true)
    {
        NavigationService.Navigate("HomePage");
    }
}

The problem with this solution is now you have one more page(Intermediate.xaml) in your backstack. Is there a way to get rid of this?

This and similar solutions don't appear to be relevant to Windows Universal Apps(Windows 8.1/Windows Phone 8.1) anymore.

Does anyone know how to implement this in the right way with MVVM?

Was it helpful?

Solution

Well, in this case MVVM doesn't hold because this should happen before a view is selected. Why don't you create a class ('Navigator' or whatever) containing your logic, and providing a property ('InitialPage') that you use in the App (instead of the hard-coded initial page) to navigate to the first page ? This way you keep your logic outside of the App class, and there is little modification to do to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top