-2

当我使用:

[Required(ErrorMessageResourceType = typeof (Resources), ErrorMessageResourceName = "MessageIISPathRequired")]
[CustomValidation(typeof (IISVM), "WebsiteRootExists", ErrorMessageResourceType = typeof (Resources), ErrorMessageResourceName = "MessageIISPathInvalid")]
public string WebsiteRoot
{
    get { return _data.WebsiteRoot; }
    set { SetProperty("WebsiteRoot", () => _data.WebsiteRoot == value, () => _data.WebsiteRoot = value); }
}

我收到一条空消息,并且在我的资源文件中该消息在那里并且是公开的。这不是 MVC 应用程序,它是 WPF 桌面应用程序,在我将其转换为使用资源之前,我的所有验证都有效。

我认为这与我如何抓住错误有关:

private static ValidationAttribute[] GetValidations(PropertyInfo property)
{
    return property.GetCustomAttributes(typeof (ValidationAttribute), true) as ValidationAttribute[];
}

private static Func<IISVM, object> GetValueGetter(PropertyInfo property)
{
    LinqExpress.ParameterExpression instance = LinqExpress.Expression.Parameter(typeof (IISVM), "i");
    LinqExpress.UnaryExpression cast =
        LinqExpress.Expression.TypeAs(LinqExpress.Expression.Property(instance, property),
                                      typeof (object));
    return (Func<IISVM, object>) LinqExpress.Expression.Lambda(cast, instance).Compile();
}

而我的IDataErrorInfo实现

public string this[string columnName]
{
    get
    {
        if (PropertyGetters.ContainsKey(columnName))
        {
            object value = PropertyGetters[columnName](this);
            string[] errors =
                Validators[columnName].Where(v => !v.IsValid(value)).Select(v => v.ErrorMessage).ToArray();
            return string.Join(Environment.NewLine, errors);
        }

        return string.Empty;
    }
}
4

1 回答 1

1

问题已修复。我不得不使用反射并在调用该方法时尝试验证该属性,而不是尝试使用上面的静态方法来计算它。

if (PropertyGetters.ContainsKey(columnName))
            {
                ValidationContext context = new ValidationContext(this, null, null)
                {
                    MemberName = columnName
                };

                List<ValidationResult> results = new List<ValidationResult>();
                var value = GetType().GetProperty(columnName).GetValue(this, null);

                return !Validator.TryValidateProperty(value, context, results)
                           ? string.Join(Environment.NewLine, results.Select(x => x.ErrorMessage))
                           : null;
            }

            return null;
于 2012-08-27T17:39:42.417 回答