本地化数据验证错误

时间:2012-08-27 16:12:56

标签: c# .net wpf idataerrorinfo

当我使用时:

[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;
    }
}

1 个答案:

答案 0 :(得分: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;