float.NaN的DataAnnotations属性

时间:2018-08-07 11:52:22

标签: c# .net wpf validation data-annotations

我正在使用DataAnnotations来验证我的ViewModel (WPF),因此,如果用户键入的内容不是浮点数,并且值超出范围。

    [Range(0, float.MaxValue, ErrorMessage = "StepSize must be more than 0")]
            public float StepSize
            {
                get { return model.StepSize; }
                set
                {                   
                    model.StepSize = value;
                    RaisePropertyChangedAndRevalidate(nameof(StepSize));
                }
            }

private void RaisePropertyChangedAndRevalidate(string propertyName)
        {
            RaisePropertyChanged(propertyName);
            if (_fieldBindingErrors == 0)
            {
                RaisePropertyChanged(nameof(IsValid));
            }
        }


        private int _fieldBindingErrors = 0;
        public ICommand RegisterFieldBindingErrors
        {
            get
            {
                return new RelayCommand<ValidationErrorEventArgs>(e =>
                {
                    if (e.Action == ValidationErrorEventAction.Added)
                    {
                        _fieldBindingErrors++;
                    }
                    else
                    {
                        _fieldBindingErrors--;
                    }
                    RaisePropertyChanged(nameof(IsValid));
                });
            }
        }

        public bool IsValid
        {
            get
            {
                bool valid = Validator.TryValidateObject(this,
                                   new ValidationContext(this, null, null),
                                   new List<System.ComponentModel.DataAnnotations.ValidationResult>())
                                   && _fieldBindingErrors == 0;

                return valid;
            }
        }

问题是,当我将textbox.Text字符串转换为float时,我必须将值设置为无效值(在不使用Range属性的情况下,也应适用于一般情况)。所以我将值设置为float.NaN。 问题在于NaN似乎是有效的浮点数,甚至可以通过上面的Range验证。

是否可以使用一个属性来验证该值不是NaN?

1 个答案:

答案 0 :(得分:1)

找到了解决方案,我创建了一个自定义验证规则,并将其应用于XAML。

  

StepSizeValidationRule类:ValidationRule      {           私人int _min;           private int _max;

    public StepSizeValidationRule()
    {
    }

    public int Min
    {
        get { return _min; }
        set { _min = value; }
    }

    public int Max
    {
        get { return _max; }
        set { _max = value; }
    }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        float stepSize = 0;

        try
        {
            if (!float.TryParse(value.ToString(), out stepSize))
            {
                return new ValidationResult(false, "Not a float");
            }

        }
        catch (Exception e)
        {
            return new ValidationResult(false, "Not a float " + e.Message);
        }

        if (float.IsNaN(stepSize))
        {
            return new ValidationResult(false, "Not a float ");
        }

        if ((stepSize < Min) || (stepSize > Max))
        {
            return new ValidationResult(false,
              "Please enter a stepSize in the range: " + Min + " - " + Max + ".");
        }
        else
        {
            return new ValidationResult(true, null);
        }
    }
}