我的ViewModel中有以下类:
public class ParentClass
{
public string Selection { get; set; }
[MyValidation]
public string ParentProperty { get; set; }
public NestedClass Nested { get; set; }
public class NestedClass
{
[MyValidation] //this doesn't have context of ParentClass inside MyValidation attribute
public string NestedProperty { get; set; }
}
}
以及以下ValidationAttribute:
public class MyValidation : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ParentClass parentClass = (ParentClass)validationContext.ObjectInstance;
if (parentClass.Selection.Equals("New"))
{
return new ValidationResult("Required");
}
return ValidationResult.Success;
}
}
[MyValidation]
可在ParentClass
属性上正常使用。但是,当我把它放在NestedClass
属性上时,我收到一个错误:
InvalidCastException: Unable to cast object of type 'NestedClass' to type 'ParentClass'.
我是否可以访问ParentClass.Selection
内的[MyValidation]
值,同时仍能将[MyValidation]
置于NestedClass
属性上?