在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的屬性時,會實時進行數據驗證,并顯示錯誤信息。