Validating model properties

Jul 5, 2011 at 8:18 AM

Hi Tony,

Here is my situation:


Class derived from SimpleMVVMToolkit base class. I have implemented INotifyDataErrorInfo interface and have also written validation rules using Validator in the model itself. The properties are decorated with Data Annotation for validation.

       private string _Name;
        [Required(ErrorMessageResourceType = typeof(ValidationResource), ErrorMessageResourceName = "OverviewModel_Name")]
        public string Name
            get { return _Name; }
                if (_Name != value)
                    ValidateProperty("Name", value);
                    _Name = value;
                    NotifyPropertyChanged(m => m.Name);

and the ValidateProperty looks like:

protected void ValidateProperty(string propertyName, object value)
            var results = new List<ValidationResult>();
            bool isValid = Validator.TryValidateProperty(value, new ValidationContext(this, null, null) { MemberName = propertyName },
            if (isValid)
                AddErrorsForProperty(propertyName, results);


I have created a viewmodel from ViewModelDetailBase and passed OverviewModel as parameter.

public class OverviewViewModel : ViewModelDetailBase<OverviewViewModel,OverviewModel>
        #region Initialization and Cleanup

        // TODO: Add a member for IXxxServiceAgent
        //private /* IXxxServiceAgent */ serviceAgent;

        // Default ctor
        public OverviewViewModel() { }

        // TODO: Ctor to set base.Model to DetailType
        public OverviewViewModel(OverviewModel model)
            base.Model = model;

        // TODO: ctor that accepts IXxxServiceAgent
        //public OverviewViewModel(/* IXxxServiceAgent */ serviceAgent)
        //    this.serviceAgent = serviceAgent;



I have created a viewmodel locator as well.

      // Create OverviewViewModel on demand
        public OverviewViewModel OverviewViewModel
            get { return new OverviewViewModel(); }


I have binding in the view as:

Value="{Binding Model.Name, Mode=TwoWay}"



Now when I run the application, I do not get any data binding/validation. I put a breakpoint at property set but it never gets there. and hence no validation as well.

Could you please let me know what my problem is and if I am doing it the right way?



Jul 5, 2011 at 9:20 AM

OK, this was pretty simple. I created a viewmodellocator but did not pass in the model as a parameter. Hence, my binding and validation was not working. It works now! My view model locator now looks like:

// Create OverviewViewModel on demand
        public OverviewViewModel OverviewViewModel
            get { return new OverviewViewModel(new OverviewModel()); }

Jul 6, 2011 at 5:24 PM

Glad it worked out. I plan to incorporate support for INotifyDataErrorInfo into the next release of the toolkit.