我試圖讓我的第一個Silverlight應用程序有史以來,但我不能讓LogOn函數工作,你能幫我嗎?這對你們來說應該是非常簡單的,我會告訴你我的兩個文件:LogOn.xaml.cs和LogOnViewModel.cs非常非常簡單的MVVM問題
顯然問題在於UserId的設置不夠早,無法在LogOn.xaml中使用.CX我需要的時候,你能不能幫我做它的工作,這將提升我的時刻了不少:-)
public partial class LogOn : PhoneApplicationPage
{
public LogOn()
{
InitializeComponent();
this.DataContext = LogOnViewModel.Instance;
}
private void btnLogOn_Click(object sender, RoutedEventArgs e)
{
if ((!string.IsNullOrEmpty(txtEmailAddress.Text)) && (!string.IsNullOrEmpty(txtPassword.Password)))
{
txbLogonMessage.Text = "";
LogOnViewModel.Instance.UserLogin(txtEmailAddress.Text, txtPassword.Password);
if (LogOnViewModel.Instance.UserId > 0)
NavigationService.Navigate(new Uri("/_2HandApp;component/Views/Main.xaml", UriKind.Relative));
else
txbLogonMessage.Text = "Login was unsuccessful. The user name or password provided is incorrect. Please correct the errors and try again. ";
}
}
}
public sealed class LogOnViewModel : INotifyPropertyChanged
{
public static LogOnViewModel Instance = new LogOnViewModel();
//public static int userId;
private SHAServiceClient WS;
private int userId;
public int UserId
{
get
{
return userId;
}
set
{
userId = value;
this.RaisePropertyChanged("UserId");
}
}
private LogOnViewModel()
{
WS = new SHAServiceClient();
WS.UserLoginCompleted += new EventHandler<UserLoginCompletedEventArgs>(WS_UserLoginCompleted);
}
void WS_UserLoginCompleted(object sender, UserLoginCompletedEventArgs e)
{
if (e.Error == null)
{
this.UserId = e.Result;
}
}
public void UserLogin(string email, string password)
{
WS.UserLoginAsync(email, password);
}
/* Implementing the INotifyPropertyChanged interface. */
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null))
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
嗨Abdou Moumen,非常感謝您的所有工作,我只需要一段時間來看看它是否可以實現它的工作。我真的很失落和沮喪,但也許在查看你的代碼並獲得MVVMLight之後,我可以開始工作,我希望如此,以後我會回來的。 – rune007 2011-05-15 18:45:56
@ rune007 silverlight是一個偉大的技術,MVVM是一個非常有趣的模式,所以保持它,祝你好運) – AbdouMoumen 2011-05-15 19:44:29
再次感謝您的詳細答案Abdou Moumen先生,您的文章是有用的,因爲我瞭解MVVM和MVVMLight: - ) – rune007 2011-05-16 07:42:32