在C#中使用MVVM模式进行数据验证可以通过以下方法实现:
- 使用INotifyDataErrorInfo接口:在ViewModel中实现INotifyDataErrorInfo接口,并在属性的setter中进行数据验证,然后通过ErrorsChanged事件通知View。
public class ViewModel : INotifyDataErrorInfo
{
private string _username;
public string Username
{
get { return _username; }
set
{
if (string.IsNullOrEmpty(value))
{
AddError("Username", "Username cannot be empty");
}
else
{
RemoveError("Username");
}
_username = value;
OnPropertyChanged("Username");
}
}
private Dictionary> _errors = new Dictionary>();
public event EventHandler ErrorsChanged;
public IEnumerable GetErrors(string propertyName)
{
if (_errors.ContainsKey(propertyName))
return _errors[propertyName];
return null;
}
public bool HasErrors => _errors.Any();
private void AddError(string propertyName, string error)
{
if (!_errors.ContainsKey(propertyName))
_errors[propertyName] = new List();
if (!_errors[propertyName].Contains(error))
{
_errors[propertyName].Add(error);
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
}
private void RemoveError(string propertyName)
{
if (_errors.ContainsKey(propertyName))
{
_errors.Remove(propertyName);
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
- 使用IDataErrorInfo接口:ViewModel类实现IDataErrorInfo接口,对属性进行数据验证,并在Error属性中返回错误信息。
public class ViewModel : IDataErrorInfo
{
private string _username;
public string Username
{
get { return _username; }
set
{
if (string.IsNullOrEmpty(value))
{
Error = "Username cannot be empty";
}
else
{
Error = null;
}
_username = value;
OnPropertyChanged("Username");
}
}
public string Error { get; private set; }
public string this[string columnName]
{
get
{
switch (columnName)
{
case "Username":
if (string.IsNullOrEmpty(Username))
return "Username cannot be empty";
break;
}
return null;
}
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
这样在View中绑定ViewModel的属性时,会实时进行数据验证,并显示错误信息。