How to handle exception in Value converter so that custom error message can be displayed

后端 未结 3 467
一生所求
一生所求 2020-12-15 19:36

I have a textbox that is bound to a class with a property of type Timespan, and have written a value converter to convert a string into TimeSpan.

If a non number is

3条回答
  •  攒了一身酷
    2020-12-15 20:11

    I used validation and converter to accept null and numbers

    XAML:

    
        
            
                
                    
                
            
        
    
    

    Code Behind:

    private void Validation_Error(object sender, ValidationErrorEventArgs e)
    {
        if (e.Action == ValidationErrorEventAction.Added)
            _noOfErrorsOnScreen++;
        else
            _noOfErrorsOnScreen--;
    }
    
    private void Confirm_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = _noOfErrorsOnScreen == 0;
        e.Handled = true;
    }
    

    ValidationRule :

    public class NumericFieldValidation : ValidationRule
    {
        private const string InvalidInput = "Please enter valid number!";
    
        // Implementing the abstract method in the Validation Rule class
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            float val;
            if (!string.IsNullOrEmpty((string)value))
            {
                // Validates weather Non numeric values are entered as the Age
                if (!float.TryParse(value.ToString(), out val))
                {
                    return new ValidationResult(false, InvalidInput);
                }
            }
    
            return new ValidationResult(true, null);
        }
    }
    

    Converter :

    public class NullableValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (string.IsNullOrEmpty(value.ToString()))
                return null;
            return value;
        }
    }
    

提交回复
热议问题