private void UpdateErrors(string propertyName, IEnumerable <string> errors) { if (errors.Any()) { if (AllPropertyErrors.ContainsKey(propertyName)) { AllPropertyErrors[propertyName].Clear(); } else { AllPropertyErrors.Add(propertyName, new List <string>()); } AllPropertyErrors[propertyName].AddRange(errors); OnErrorsChanged(propertyName); } else { if (AllPropertyErrors.ContainsKey(propertyName)) { AllPropertyErrors.Remove(propertyName); } OnErrorsChanged(propertyName); } }
/// <summary> /// Gets the validation errors for a specified property or for the entire entity. /// </summary> /// <param name="propertyName">The name of the property to retrieve validation error messages for; or null or Empty, to retrieve entity-level errors.</param> /// <returns>The validation error messages for the property or entity.</returns> public IEnumerable GetErrors(string propertyName) { List <string> propertyErrors = new List <string>(); if (string.IsNullOrEmpty(propertyName)) { return(propertyErrors); } AllPropertyErrors.TryGetValue(propertyName, out propertyErrors); return(propertyErrors); }
private void AddValidationError(string propertyName, string error) { if (AllPropertyErrors.ContainsKey(propertyName)) { if (!AllPropertyErrors[propertyName].Contains(error)) { AllPropertyErrors[propertyName].Add(error); OnErrorsChanged(propertyName); } } else { AllPropertyErrors.Add(propertyName, new List <string>() { error }); OnErrorsChanged(propertyName); } }
/// <summary> /// Updates the errors in the AllPropertyErrors property collection and raises the ErrorsChanged event dependent upon the contents of the collection specified by the errors input parameter. /// </summary> /// <param name="propertyName">The name of the property to validate.</param> /// <param name="errors">The collection of error messages relating to the property specified by the propertyName input parameter.</param> private void Validate(string propertyName, IEnumerable <string> errors) { if (ValidationLevel == ValidationLevel.None) { return; } ValidationContext validationContext = new ValidationContext(this); List <ValidationResult> validationResults = new List <ValidationResult>(); Validator.TryValidateObject(this, validationContext, validationResults, true); IEnumerable <ValidationResult> propertyValidationResults = validationResults.Where(v => v.MemberNames.Contains(propertyName)); propertyValidationResults.ForEach(v => AddValidationError(propertyName, v.ErrorMessage)); if (errors.Any()) { errors.ForEach(e => AddValidationError(propertyName, e)); } else if (propertyValidationResults.Count() == 0 && AllPropertyErrors.ContainsKey(propertyName)) { RemoveValidationError(propertyName); } NotifyPropertyChanged(nameof(Errors), nameof(HasErrors)); }
private void RemoveValidationError(string propertyName) { AllPropertyErrors.Remove(propertyName); OnErrorsChanged(propertyName); }