-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Description
Describe the bug
When you implement the MVVM pattern, is usual to implement the interface INotifyDataErrorInfo.
public interface INotifyDataErrorInfo
{
bool HasErrors { get; }
event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
IEnumerable GetErrors(string propertyName);
}This interface returns the error of the ViewModel as a non generic IEnumerable. By definition, this IEnumerable can contain ANY object, not just strings. For example, the Library Microsoft.Toolkit.Mvvm implements the interface in the following way:
//
// Summary:
// A base class for objects implementing the System.ComponentModel.INotifyDataErrorInfo
// interface. This class also inherits from Microsoft.Toolkit.Mvvm.ComponentModel.ObservableObject,
// so it can be used for observable items too.
public abstract class ObservableValidator : ObservableObject, INotifyDataErrorInfo
{
public bool HasErrors { get; }
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
public IEnumerable<ValidationResult> GetErrors(string? propertyName = null);
// Other methods for setting properties and validation
// [ ... ]
protected void ValidateAllProperties();
protected internal void ValidateProperty(object? value, [CallerMemberName] string? propertyName = null);
}This library returns an enumerable of System.ComponentModel.DataAnnotations.ValidationResult. But it could be any object.
The problem is that in the newer version of HandyControl, all input fields support Validation, but they assume the contents of the IEnumerable are strings:
HandyControl/src/Shared/HandyControl_Shared/Controls/Input/TextBox.cs
Lines 123 to 127 in 5dcb6dc
| isError = Validation.GetHasError(this); | |
| if (isError) | |
| { | |
| SetCurrentValue(ErrorStrProperty, Validation.GetErrors(this)[0].ErrorContent); | |
| } |
So, this exception is thrown, because System.ComponentModel.DataAnnotations.ValidationResult is not a string.
System.ArgumentException: ''The Password field is required.' is not a valid value for property 'ErrorStr'.'
The correct way, would be:
isError = Validation.GetHasError(this);
if (isError)
{
SetCurrentValue(ErrorStrProperty, Validation.GetErrors(this)[0].ErrorContent?.ToString());
}To Reproduce
Implement INotifyDataErrorInfo with GetErrors returning an IEnumerable of custom error objects instead of strings and an exception will be thrown.
Environment (please complete the following information):
- .net: net5
- IDE vs2019
- Version HandyControls 3.3.8 (I use the forked version, but I think this bug report goes here)