0

我想在 App.xaml.cs 类中进行身份验证,如果用户存在于数据库中,我想将用户引导到成员页面,否则想引导用户公共页面。我知道如何使用 rootframe 导航,但问题是即使我的 webervice 异步方法是在 RootFrameNavigating 之前编写的,但它没有在它之前执行。我的代码在这里

在 App 构造函数中

        dclient.GetUserByPhoneIdCompleted += new EventHandler<GetUserByPhoneIdCompletedEventArgs> (dclient_GetUserByPhoneIdCompleted);
        dclient.GetUserByPhoneIdAsync(GetDeviceUniqueID());
        if (getUserbyPhoneIdCompleted)
              RootFrame.Navigating += new NavigatingCancelEventHandler(RootFrame_Navigating);

在我的方法中

        if (e.Uri.ToString().Contains("/MainPage.xaml") != true)
            return;
        e.Cancel = true;

        RootFrame.Dispatcher.BeginInvoke(delegate
        {
            if (userId == -1)
                RootFrame.Navigate(new Uri(string.Format("/View/PublicPage.xaml"), UriKind.Relative));
            else
                RootFrame.Navigate(new Uri(string.Format("/View/WelcomePage.xaml"), UriKind.Relative));
        });

并在我的webservice方法中返回整数,我在那里得到用户ID

像这样

 void dclient_GetUserByPhoneIdCompleted(object sender, GetUserByPhoneIdCompletedEventArgs e)
 {
     userId = e.Result;
     getUserbyPhoneIdCompleted = true; 
 }
4

1 回答 1

0

Your application starts, you send an asynchronous call to the webservice. Then the navigating event is triggered (why wouldn't it be? You're not blocking the thread), and your event handler is called. There, you're canceling the navigation, and checking the value returned by the webservice. But since there isn't any kind of waiting, you can reach that point before the webservice call has ended. There's many ways to fix that, but the one I would recommend is:

  • Don't call the webservice at application startup, let the application navigate to a custom loading page
  • On that page, call the webservice and display a 'Loading' message
  • Using the result of the webservice call, redirect to whichever page you want, then remove the loading page from the backstack

Don't forget to handle the case when the webservice call returns an error.

于 2012-05-16T09:22:32.383 回答