Skip to content

Instantly share code, notes, and snippets.

@hidekuro
Last active October 27, 2017 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hidekuro/f3fedcc21bc493e481255d2faf235d24 to your computer and use it in GitHub Desktop.
Save hidekuro/f3fedcc21bc493e481255d2faf235d24 to your computer and use it in GitHub Desktop.
INotifyDataErrorInfoをサポートするBindableBase
/// <summary>
/// INotifyDataErrorInfoをサポートするBindableBase
/// </summary>
class ValidatableModelBase : BindableBase, INotifyDataErrorInfo
{
private ErrorsContainer<string> _errors;
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public IEnumerable GetErrors(string propertyName)
{
return _errors.GetErrors(propertyName);
}
public bool HasErrors
{
get { return _errors.HasErrors; }
}
public ValidatableModelBase()
{
_errors = new ErrorsContainer<string>(OnErrorsChanged);
}
private void OnErrorsChanged([CallerMemberName] string propertyName = null)
{
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
protected void ValidateProperty(object value, [CallerMemberName] string propertyName = null)
{
var context = new ValidationContext(this)
{
MemberName = propertyName
};
var validationErrors = new List<ValidationResult>();
if (!Validator.TryValidateProperty(value, context, validationErrors))
{
_errors.SetErrors(propertyName, validationErrors.Select(error => error.ErrorMessage));
}
else
{
_errors.ClearErrors(propertyName);
}
}
}
@hidekuro
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment