【发布时间】:2011-02-04 15:26:37
【问题描述】:
我想知道在视图模型中正确使用模型类的方法。作为 MVVM,我使用 Caliburn Micro。
第一种选择。
模型类:
public class CurrentUser : IDataErrorInfo
{
public string Nick { get; set; }
public string Password { get; set; }
//...
}
在视图模型类中使用模型:
[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);
}
}
}
第二种选择:
模型类:
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");
}
}
//...
}
在视图模型类中使用模型类:
[Export(typeof(ILogOnViewModel))]
public class LogOnViewModel : Screen
{
//bind on UI control
public CurrentUser CurrentUser { get; set; }
}
【问题讨论】:
-
您可以通过使用深度属性绑定来大大缩短第一种方法,即,只需将元素绑定命名为“CurrentUser”“CurentUser_Nick”的“Nick”字符串(对于 CurrentUser_Password 也是如此) - 然后你根本不需要属性“CurrentNick”和“CurrentPassword”(不过,请将 NotifyOfPropertyChange 添加到 CurrentUser)。
标签: wpf mvvm caliburn.micro