using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace PLCSharp.Core.Prism
{
///
/// ValidateBase
///
public class ValidateBase : ViewModelBase, IDataErrorInfo
{
#region 属性
private readonly Dictionary dataErrors = [];
///
/// 是否验证通过
///
public bool IsValidated
{
get
{
if (dataErrors != null && dataErrors.Count > 0)
{
return false;
}
return true;
}
}
#endregion 属性
///
/// this[]
///
/// column名称
public string this[string columnName]
{
get
{
ValidationContext vc = new(this, null, null)
{
MemberName = columnName
};
var res = new List();
var result = Validator.TryValidateProperty(GetType().GetProperty(columnName).GetValue(this, null), vc, res);
if (res.Count > 0)
{
AddDic(dataErrors, vc.MemberName);
return string.Join(Environment.NewLine, [.. res.Select(r => r.ErrorMessage)]);
}
RemoveDic(dataErrors, vc.MemberName);
return null;
}
}
///
/// 错误
///
public string Error
{
get
{
return null;
}
}
#region 附属方法
private static void RemoveDic(Dictionary dics, string dicKey)
{
dics.Remove(dicKey);
}
private static void AddDic(Dictionary dics, string dicKey)
{
dics.TryAdd(dicKey, "");
}
#endregion 附属方法
}
}