Last active
October 27, 2017 05:27
-
-
Save hidekuro/f3fedcc21bc493e481255d2faf235d24 to your computer and use it in GitHub Desktop.
INotifyDataErrorInfoをサポートするBindableBase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks: https://qiita.com/Koki_jp/items/ae00c525728b81f302b8