Data Annotations, IDataErrorInfo and MVVM

前端 未结 2 1173
我寻月下人不归
我寻月下人不归 2021-01-26 05:29

I\'m trying to find the best way to validate data in MVVM. Currently, I\'m trying to use IDataErrorInfo with Data Annotations using the MVVM pattern.

However, nothing se

2条回答
  •  被撕碎了的回忆
    2021-01-26 06:27

    To keep validation running, IDataErrorInfo must be implemented by the data context, which property is bound to the control. So, it should be something like:

    public class PersonViewModel : IDataErrorInfo 
    {
        [Required(AllowEmptyStrings = false)]
        public string Name
        {
            get
            {
                 return _person.Name
            }
            set
            {
                 _person.Name = value;
            }
        }    
    
        public string Error
        {
            get { throw new NotImplementedException(); }
        }
    
        string IDataErrorInfo.this[string propertyName]
        {
            get
            {
                return OnValidate(propertyName);
            }
        }
    
        protected virtual string OnValidate(string propertyName)
        {
            /* ... */
        }
    }
    

    There's no need to implement IDataErrorInfo in model, this is view model's responsibility. Usually, IDataErrorInfo is implemented by the base class for your view models.

    By the way, why OnValidate is protected? How do you imagine overriding of this method?

提交回复
热议问题