当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Navigating to another pages using navigation service with MVVM from the constructor

问题描述:

I'm developing a universal app using MVVM (light) and I'm trying to integrate OneDrive using the SDK. Each of my pages have a ViewModel associated with them.

I have a start up page (OneDrivePromptPage) where I offer the user to either sign in to Microsoft OneDrive or skip the sign in process.

When the user clicks on the Skip button, it calls the relevant command in my OneDrivePromptViewModel and navigates to my MainPage by calling:

this._navigationService.Navigate(typeof(MainPage));

The same applies when the user clicks on the Sign button and it prompts the user for their OneDrive credentials and if successfully logged in, it navigates to my 'MainPage'.

Now, here's my problem. When signs in successfully to OneDrive, I set a flag (IsSignedIn=true) to a container and save it to my storage (RoamingSettings).

All of the above works fine but I'm facing a problem where when I start the application again, it checks OneDrivePromptViewModel's constructor if the IsSignedIn value from the storage is set to true. If it is, I'll try to automatically sign in to OneDrive. If successful, I want to navigate to my 'MainPage' but this won't work.

It calls the same navigate code as above, doesn't throw any errors but it doesn't navigate to my 'MainPage' and ends up displaying my "Prompt" page.

public OneDrivePromptViewModel(INavigationService navigationService,

ISettingsDataService settingsDataService)

{

this._navigationService = navigationService;

this._settingsDataService = settingsDataService;

bool isSignedIn = false;

isSignedIn = this._settingsDataService.

GetItem<bool>("MyStoreApp", "IsSignedIn");

if (isSignedIn && !MyOneDrive.IsSignedIn())

{

ExecuteSignInCommand();

}

else if (isSignedIn && MyOneDrive.IsSignedIn())

{

NavigateToMainPage();

}

}

Any ideas why it's not navigating to the relevant page. Is it because I'm calling this from the constructor. If that's not the correct place to call it from, where should I call this from?

I'm not even sure, I should be loading the OneDrivePromptPage? Should I be performing this checks in a method of some sort before loading either OneDrivePromptPage or MainPage and perform the same checks mentioned above, but where do I put this method? In my App.cs?

Thanks.

网友答案:

In a recent Universal app I check for something similar, but initiate this in the OnLaunched event of the App.xaml.cs

Making sure based on the isSignedIn check that I navigate to the correct page like so:

bool navigated = rootFrame.Navigate(isSignedIn ? typeof(MainPage) : typeof(PromptPage);

You could try to see if this also works in your scenario

分享给朋友:
您可能感兴趣的文章:
随机阅读: