我想知道在视图模型中使用模型类的正确方法.作为MVVM,我使用Caliburn Micro.
第一种选择.
型号类:
public class CurrentUser : IDataErrorInfo
{
public string Nick { get; set; }
public string Password { get; set; }
//...
}
Run Code Online (Sandbox Code Playgroud)
在视图模型类中使用模型:
[Export(typeof(ILogOnViewModel))]
public class LogOnViewModel : Screen
{
public CurrentUser CurrentUser { get; set; }
//bind on control in view
public string CurrentNick
{
get { return CurrentUser.Nick; }
set
{
CurrentUser.Nick = value;
NotifyOfPropertyChange(() => CurrentNick);
}
}
//bind on control in view
public string CurrentPassword
{
get { return CurrentUser.Password; }
set
{
CurrentUser.Password = value;
NotifyOfPropertyChange(() => CurrentPassword);
}
}
}
Run Code Online (Sandbox Code Playgroud)
第二种选择:
型号类:
public class CurrentUser : IDataErrorInfo, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public string Nick
{
get { return _nick; }
set
{
_nick = value;
NotifyPropertyChanged("Nick");
}
}
public string Password
{
get { return _password; }
set
{
_password = value;
NotifyPropertyChanged("Password");
}
}
//...
}
Run Code Online (Sandbox Code Playgroud)
在视图模型类中使用模型类:
[Export(typeof(ILogOnViewModel))]
public class LogOnViewModel : Screen
{
//bind on UI control
public CurrentUser CurrentUser { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
第一种选择会更好,因为它从View中更好地封装了你的模型.
但是,你应该实现IDataErrorInfo并INotifyPropertyChanged在视图模型,因为视图模型应该是通知的变化和错误的用户界面对象.
我更喜欢第一种方法.有几个原因:
Model永远不应该被访问View.ViewModel包裹/墙面需要绑定到所有属性View的Model.它添加了促进View功能所需的任何其他属性,集合和命令,同时防止将代码放入代码中.IDataErrorInfo和INotifyPropertyChanged促进View不ViewModel.因为View只与ViewModel他们沟通,所以他们应该在里面ViewModel.