在C#中使用MVVM模式进行数据验证可以通过以下方法实现:
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<string, List<string>> _errors = new Dictionary<string, List<string>>();
public event EventHandler<DataErrorsChangedEventArgs> 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<string>();
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));
}
}
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的属性时,会实时进行数据验证,并显示错误信息。