Answer the question
In order to leave comments, you need to log in
Binding to a double property + validation?
I use this class for validation:
public abstract class ViewModelBase : INotifyPropertyChanged, IDataErrorInfo
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly HashSet<string> PropertiesWithErrors = new HashSet<string>();
protected bool HasValidationErrors { get { return PropertiesWithErrors.Any(); } }
public string this[string propertyName] { get { return Validate(propertyName); } }
public string Error { get { throw new NotImplementedException(); } }
protected virtual string Validate(string propertyName)
{
var value = GetType().GetProperty(propertyName).GetValue(this);
var results = new List<ValidationResult>();
var context = new ValidationContext(this, null, null) { MemberName = propertyName };
if (!Validator.TryValidateProperty(value, context, results))
{
PropertiesWithErrors.Add(propertyName);
return results.First().ErrorMessage;
}
PropertiesWithErrors.Remove(propertyName);
return string.Empty;
}
protected virtual void RaisePropertyChanged(string pname) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(pname));
protected virtual void Set<T>(string pname, ref T field, T value)
{
field = value;
RaisePropertyChanged(pname);
}
}
public class ViewModel : ViewModelBase
{
public double Value { get; set; }
}
<TextBox Text="{Binding Path=Value, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}"/>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question