1.定义ValidateModelBase 基类,实现IDataErrorInfo接口来触发验证信息,
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using CommunityToolkit.Mvvm.ComponentModel;
public class ValidateModelBase : ObservableObject, IDataErrorInfo
{
public ValidateModelBase()
{
DataErrors = new Dictionary<string, string>();
}
#region 属性
public Dictionary<string, string>? DataErrors { get; private set; } = new Dictionary<string, string>();
public bool IsValidated
{
get
{
return DataErrors?.Count == 0;
}
}
private bool _shouldValidate = false;
#endregion 属性
public string this[string columnName]
{
get
{
if (!_shouldValidate)
return string.Empty;
if (columnName == null) throw new ArgumentNullException(nameof(columnName));
ValidationContext vc = new ValidationContext(this, null, null)
{
MemberName = columnName
};
var res = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
var propertyInfo = this.GetType().GetProperty(columnName);
if (propertyInfo == null)
{
return string.Empty;
}
var value = propertyInfo.GetValue(this, null);
bool result = Validator.TryValidateProperty(value, vc, res);
if (res.Count > 0)
{
string errorInfo = string.Join(Environment.NewLine, res.Select(r => r.ErrorMessage).ToArray());
AddDic(DataErrors, columnName, errorInfo);
return errorInfo;
}
RemoveDic(DataErrors, columnName);
return string.Empty;
}
}
public string Error => string.Empty;
#region 附属方法
private void RemoveDic(Dictionary<string, string>? dics, string dicKey)
{
if (dics != null)
{
dics.Remove(dicKey);
}
}
private void AddDic(Dictionary<string, string>? dics, string dicKey, string dicValue)
{
if (dics != null && !dics.ContainsKey(dicKey))
{
dics.Add(dicKey, dicValue);
}
}
#endregion 附属方法
public bool Validate()
{
_shouldValidate = true;
this.GetType().GetProperties()
.Where(prop => prop.GetCustomAttributes(false)
.Any(attr => attr.GetType().Namespace == typeof(RequiredAttribute).Namespace))
.ToList().ForEach(p => OnPropertyChanged(p.Name));
return IsValidated;
}
}