在另一个测试用的小例子中是可以正常运行的,在项目中之前也是可以正常运行的,只不过当时控件是在Popup中,后来本人把他们挪到了另一个模态窗体中之后,就不起作用了,不知道怎么搞的。
Person类(包括验证Attribute):
Person类(包括验证Attribute):
public class Person : IDataErrorInfo
{
public string Name { get; set; }
public class PersonMetadata
{
[CustomValidation(typeof(ValidationUtils), "CheckName")]
public string Name { get; set; }
}
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
return this.ValidateProperty<PersonMetadata>(columnName);
}
}
}
那个拓展方法ValidateProperty<T>是网上找来的那个,基本是这几步:
public static class ValidationExtension
{
public static string ValidateProperty<MetadataType>(this object obj, string PropertyName)
{
Type targetType = obj.GetType();
var associatedProvider =
new AssociatedMetadataTypeTypeDescriptionProvider(targetType, typeof(MetadataType));
//添加伴随类
TypeDescriptor.AddProviderTransparent(associatedProvider, targetType);
var propertyValue = targetType.GetProperty(PropertyName).GetValue(obj, null);
var validationContext = new ValidationContext(obj, null, null);
validationContext.MemberName = PropertyName;
var validationResults = new List<ValidationResult>();
Validator.TryValidateProperty(propertyValue, validationContext, validationResults);
if (validationResults.Count > 0)
{
return validationResults.First().ErrorMessage;
}
else
{
return string.Empty;
}
}
}
在测试用的例子中,都是可以正常进到验证类的构造函数中
public class ValidationUtils
{
static ValidationUtils()
{
//测试例子中可以正常进到这里
}
public static ValidationResult ChechName(string name)
{
return ValidationResult.Success;
}
}
把控件和ViewModel挪到新的View和ViewModel中以后,就特喵的不行了,ValidateProperty拓展方法都是正常触发的,但是每次到了 Validator.TryValidateProperty 这里之后,都是运行一下就过了,也不报错,返回的也是 true,可就是不进验证的那个方法类中,这到底是为啥捏
解决方案:30分
public class ValidationUtils
{
static ValidationUtils()
{
//测试例子中可以正常进到这里
}
{
static ValidationUtils()
{
//测试例子中可以正常进到这里
}
public static ValidationResult CheckName(string name)
{
return ValidationResult.Success;
}
}