【问题标题】:Localize Data validation errors本地化数据验证错误
【发布时间】:2012-08-27 16:12:56
【问题描述】:

当我使用时:

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

【问题讨论】:

    标签: c# .net wpf idataerrorinfo


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 2013-02-21
      相关资源
      最近更新 更多