D
D
DarkByte20152016-04-22 13:54:42
WPF
DarkByte2015, 2016-04-22 13:54:42

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);
        }
    }

You just need to inherit the ViewModel from it and create a property for binding. This is very convenient, because it is immediately clear whether there are validation errors. But I have such a problem. If I have a property of type double, then dots and commas completely cease to be entered. How can I put a fractional dot (or comma)?
Well, for example:
public class ViewModel : ViewModelBase
{
    public double Value { get; set; }
}

<TextBox Text="{Binding Path=Value, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}"/>

In addition, when working with this ViewModel, any useful attributes from System.ComponentModel.DataAnnotations ala Range, etc. stop working. Why is this happening?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question