0

I want to create a login page where the users enters username/password then a web service authenticates and saves an authentication token retrieved from the server.

I want the page view to be notified when the authentication is done successfully.

my question is: how to implement this in MVVM pattern ? I created a class for the model, a class for the model view and a class for the calling and parsing of the web service.

I can't set my ModelView as a DataContext for the page cause there are no controls that bind to the Model's data.

is this pattern an overkill or it can be implemented in another way ? please suggest.

Thanks

4

2 回答 2

2

我有一个按照此处所述实现的登录页面。登录页面本身没有视图模型,但它确实使用了我编写的服务,其中包含登录完成时的回调。该服务还包含有关用户的其他有用信息。我认为 MVVM 在这里会有点矫枉过正。

    private void LoginButton_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(EmailTextBox.Text)) return;
        if (string.IsNullOrEmpty(PasswordTextBox.Password)) return;

        Login();
    }

    private void Login()
    {
        if (DeviceNetworkInformation.IsNetworkAvailable == false)
        {
            MessageBox.Show("I'm having trouble connecting to the internet." + Environment.NewLine + "Make sure you have cell service or are connected to WiFi then try again");
        }
        else
        {
            LoginButton.Focus(); // Removes the keyboard
            UserProfile.Name = EmailTextBox.Text;
            UserProfile.Password = PasswordTextBox.Password;

            UserProfile.Current.Login(result =>
                {
                    // callback could be on another thread
                    Dispatcher.BeginInvoke(() =>
                        {
                            // Did the login succeed?
                            if (result.Result)
                            {
                                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                            }
                            else
                            {
                                string message = "Sorry, but I was not able to log in that user. Please make sure the name and password were entered correctly.";
                                MessageBox.Show(message, "Login failed");
                            }
                        });
                });
        }
    }
于 2012-07-27T14:30:19.207 回答
2

您需要ICommand在 ViewModel 中放置 s 来指向执行调用您的 Web 服务的方法,并且您的 View 中的元素应该绑定到这些命令以执行操作。

而且您的视图模型中还需要一个布尔属性:IsLoggedIn,当对您的 Web 服务的登录调用返回成功时,您将其设置为 true。

然后在您看来,您可以绑定到 IsLoggedIn 以向您的用户提供反馈。

注意:不要忘记在其设置器中为 IsLoggedIn 提高 PropertyChanged。

于 2012-07-26T10:10:37.417 回答