问候,
我无法进行验证工作。 在不同的模型中,它在调用以下扩展方法时非常有效:
public static bool IsValid(this Entity entity, bool validate = false)
{
List<ValidationResult> result = entity.IsValid();
return (result.Count == 0);
}
public static List<ValidationResult> IsValid(this Entity entity)
{
var validationResult = new List<ValidationResult>();
if (entity != null)
{
validationResult = entity.ValidateEntity();
Validator.TryValidateObject(entity, new ValidationContext(entity, null, null), validationResult, true);
}
return validationResult;
}
private static List<ValidationResult> ValidateEntity(this Entity entity, int depth = 0)
{
var validationResult = new List<ValidationResult>();
if (entity != null && depth < 4)
{
foreach (var propertyInfo in entity.GetType().GetProperties())
{
if (propertyInfo.PropertyType.BaseType == typeof(Entity))
{
var value = propertyInfo.GetValue(entity, null) as Entity;
if (value != null)
{
Validator.TryValidateObject(value, new ValidationContext(value, null, null), validationResult, true);
var result = value.ValidateEntity(++depth);
if (result.Count > 0)
{
validationResult.AddRange(result);
}
}
}
}
}
return validationResult;
}
然而,当我在不同的模型上使用它时,它具有大致相同的结构, 当属性为空时,它会返回错误列表,但它不会为我的文本框提供包含错误消息的红色边框。
部分模型不起作用:
[Display(Name = "Reden")]
[Required(ErrorMessage = "Reden is een verplicht veld")]
[StringLength(50, ErrorMessage = "Het veld mag maximaal 50 karakters bevatten")]
public string Reason { get; set; }
我缺少什么使这项工作正常?
[编辑]
[XAML]
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectedNoFacility.Reason, Mode=TwoWay}" Margin="5" Grid.ColumnSpan="4" />
[/ XAML]
[/编辑]