验证过早发射

时间:2011-11-01 13:22:58

标签: wpf c#-4.0 mvvm

我为我的视图模型构建了一个基类。以下是部分代码:

public class BaseViewModel<TModel> : DependencyObject, INotifyPropertyChanged, IDisposable, IBaseViewModel<TModel>, IDataErrorInfo
{
        public TModel Model { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (this._disposed)
            {
                return;
            }

            if (disposing)
            {
                this.Model = default(TModel);
            }

            this._disposed = true;
        }
}

好的,所以我想,让我们在基类中添加一些验证,这使我得到了以下文章:Prism IDataErrorInfo validation with DataAnnotation on ViewModel Entities。所以我将以下方法/属性(IDataErrorInfo)添加到我的基类:

string IDataErrorInfo.Error
{
    get { return null; }
}

string IDataErrorInfo.this[string columnName]
{
    get { return ValidateProperty(columnName); }
}

protected virtual string ValidateProperty(string columnName)
{
    // get cached property accessors
    var propertyGetters = GetPropertyGetterLookups(GetType());

    if (propertyGetters.ContainsKey(columnName))
    {
        // read value of given property
        var value = propertyGetters[columnName](this);

        // run validation
        var results = new List<ValidationResult>();
        var vc = new ValidationContext(this, null, null) { MemberName = columnName };
        Validator.TryValidateProperty(value, vc, results);

        // transpose results
        var errors = Array.ConvertAll(results.ToArray(), o => o.ErrorMessage);
        return string.Join(Environment.NewLine, errors);
    }
    return string.Empty;
}

private static Dictionary<string, Func<object, object>> GetPropertyGetterLookups(Type objType)
{
    var key = objType.FullName ?? "";
    if (!PropertyLookupCache.ContainsKey(key))
    {
        var o = objType.GetProperties()
        .Where(p => GetValidations(p).Length != 0)
        .ToDictionary(p => p.Name, CreatePropertyGetter);

        PropertyLookupCache[key] = o;
        return o;
    }
    return (Dictionary<string, Func<object, object>>)PropertyLookupCache[key];
}

private static Func<object, object> CreatePropertyGetter(PropertyInfo propertyInfo)
{
    var instanceParameter = System.Linq.Expressions.Expression.Parameter(typeof(object), "instance");

    var expression = System.Linq.Expressions.Expression.Lambda<Func<object, object>>(
        System.Linq.Expressions.Expression.ConvertChecked(
            System.Linq.Expressions.Expression.MakeMemberAccess(
                System.Linq.Expressions.Expression.ConvertChecked(instanceParameter, propertyInfo.DeclaringType),
                propertyInfo),
            typeof(object)),
        instanceParameter);

    var compiledExpression = expression.Compile();

    return compiledExpression;
}

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

好的,这让我想到了这个问题。事情是验证工作完美,但是假设我有一个带有StringLength属性的属性(在我的视图模型中称为:Person)。一旦打开应用程序,就会触发StringLength属性。用户甚至没有机会做任何事情。一旦应用程序启动,验证就会触发。

public class PersonViewModel : BaseViewModel<BaseProxyWrapper<PosServiceClient>>
{
    private string _password = string.Empty;
    [StringLength(10, MinimumLength = 3, ErrorMessage = "Password must be between 3 and 10 characters long")]
    public string Password
    {
        get { return this._password; }
        set
        {
            if (this._password != value)
            {
                this._password = value;
                this.OnPropertyChanged("Password");
            }
        }
    }
}

我注意到这是由IDataErrorInfo.this[string columnName]属性引起的,而后者又调用了ValidateProperty方法。但是,我不知道如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

可能有两个问题......

您是否使用公共属性填充yopur Person实例?

e.g。

  new Person { Password = null }

这将触发密码的属性更改通知,并将验证它。

一些开发人员还在构造函数中设置属性......

public class Person {
   public Person() {
      this.Password = null;
   }
} 

建议的做法是使用私人字段......

public class Person {
   public Person() {
      _password = null;
   }

   public Person(string pwd) {
      _password = pwd;
   }
} 

OR

您可以在我们的视图模型库中创建一个标记IsLoaded。确保在加载UI后(可能在UI.Loaded事件中)将其设置为true。在IDataErrorInfo.this[string columnName]中检查此属性是否为true,然后才验证值。否则返回null。

[编辑]

以下更改完成了这项工作:

public class PersonViewModel : BaseViewModel<BaseProxyWrapper<PosServiceClient>>
{
    private string _password;
    [StringLength(10, MinimumLength = 3, ErrorMessage = "Password must be between 3 and 10 characters long")]
    public string Password
    {
        get { return this._password; }
        set
        {
            if (this._password != value)
            {
                this._password = value;
                this.OnPropertyChanged("Password");
            }
        }
    }

    public PersonViewModel(BaseProxyWrapper<PosServiceClient> model)
        : base(model)
    {
        this._username = null;
    }
}

答案 1 :(得分:0)

我过去做过的事情是将更新源触发器更改为显式,创建一个在TextBox失去焦点时更新源的行为,然后将该行为附加到TextBox。