因此,对于MVVM架构如何为我提供帮助以及在这种情况下如何使用它,我有些困惑:
我正在使用Xamarin,并在iOS中创建了我的视图和视图控制器作为示例.我还实现了MVVMLight工具包,并为视图和视图控制器创建了ViewModel.
我正在创建一个登录屏幕,因此用户输入其用户名和密码,并通过RaisePropertyChanged()事件在模型中对其进行更新.我的问题是我需要在哪里调用该函数来验证此信息并将其实际登录到系统中?
我已经实现了RelayCommand,就像我在其他教程中看到的那样,每当单击按钮时,都会在ViewModel上调用方法,但是我不确定是否应该在此处调用验证代码.
我所拥有的一些例子:
LoginViewModel.cs:
public class LoginViewModel : ViewModelBase
{
private string _username;
private string _password;
public RelayCommand LoginButtonCommand { get; private set; }
public bool CanExecuteLoginCommand { get; set; }
public LoginViewModel()
{
LoginButtonCommand = new RelayCommand(HandleLoginButtonCommand, () => CanExecuteLoginCommand);
CanExecuteLoginCommand = true;
}
public string Username
{
get
{
return _username;
}
set
{
_username = value;
RaisePropertyChanged(() => Username);
}
}
public string Password
{
get
{
return _password;
}
set
{
_password = value;
RaisePropertyChanged(() => Password);
}
}
private void HandleLoginButtonCommand()
{
CanExecuteLoginCommand = false;
//Validate login?
CanExecuteLoginCommand = true;
}
}
LoginViewController.cs:
public partial class LoginViewController : UIViewController
{
private Binding _usernameTextFieldBinding;
private Binding _passwordTextFieldBinding;
private LoginViewModel _viewModel;
public LoginViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
_viewModel = Application.Locator.Login;
HideKeyboardHandling(UsernameTextField);
HideKeyboardHandling(PasswordTextField);
_usernameTextFieldBinding = this.SetBinding(
() => _viewModel.Username)
.ObserveSourceEvent("EditingDidEnd")
.WhenSourceChanges(() => _viewModel.Username = UsernameTextField.Text);
_passwordTextFieldBinding = this.SetBinding(
() => _viewModel.Username)
.ObserveSourceEvent("EditingDidEnd")
.WhenSourceChanges(() => _viewModel.Password = PasswordTextField.Text);
Loginbutton.SetCommand("TouchUpInside", _viewModel.LoginButtonCommand);
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
void HideKeyboardHandling(UITextField textField)
{
textField.ShouldReturn = TextField =>
{
TextField.ResignFirstResponder();
return true;
};
var gesture = new UITapGestureRecognizer(() => View.EndEditing(true));
gesture.CancelsTouchesInView = false;
View.AddGestureRecognizer(gesture);
}
}
解决方法:
这完全取决于您对“单一责任原则”(SPR)的严格要求.而这又取决于应用程序的复杂程度.应用程序越复杂,职责应该越分开.
典型的MVVM实现可处理ViewModel中的命令.然后ViewModel将调用转发到Model中.但是他仍然将两个职责(例如表示和命令处理)放在一个单独的组件中,也就是ViewModel.
一种更严格的方法是让ViewModel只处理表示逻辑.创建一个单独的控制器来承载所有命令处理程序.并让命令处理程序将调用转发给模型.
更为宽松的方法是在ViewModel中简单地实现业务逻辑.这意味着您没有业务逻辑层.如果您的应用程序足够简单,以至于业务逻辑层不值得您花精力,那很好.