Josh Smith Way is to create the following methods in a model:
static readonly string[] ValidatedProperties = { "Foo", "Bar" }; /// <summary> /// Returns true if this object has no validation errors. /// </summary> public bool IsValid { get { foreach (string property in ValidatedProperties) { if (GetValidationError(property) != null) // there is an error return false; } return true; } } private string GetValidationError(string propertyName) { string error = null; switch (propertyName) { case "Foo": error = this.ValidateFoo(); break; case "Bar": error = this.ValidateBar(); break; default: error = null; throw new Exception("Unexpected property being validated on Service"); } return error; }
ViewModel then contains the CanSave property, which reads the IsValid property on the model:
/// <summary> /// Checks if all parameters on the Model are valid and ready to be saved /// </summary> protected bool CanSave { get { return modelOfThisVM.IsValid; } }
Finally, if you use RelayCommand , you can set the command predicate to the CanSave property, and the view will automatically enable or disable this button. In ViewModel:
/// <summary> /// Saves changes Command /// </summary> public ICommand SaveCommand { get { if (_saveCommand == null) _saveCommand = new RelayCommand(param => this.SaveChanges(), param => this.CanSave); return _saveCommand; } }
And in the view:
<Button Content="Save" Command="{Binding Path=SaveCommand}"/>
What is it!
PS: If you havenβt read the article by Josh Smith, it will change your life.
Pieter mΓΌller
source share