WPF MVVM Textbox Validation

前端 未结 2 503
别跟我提以往
别跟我提以往 2021-02-08 11:27

I\'m creating a WPF application using MVVM. I have a textbox, which is bound to a property in my ViewModel of type double with a default value of 0.0. If I now ente

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-08 12:02

    You can attach a Validation Rule to the binding of the textbox that checks if the value is a valid double. This will prevent the user from being able to press the Submit button unless a valid value is entered thereby eliminating your need to check if the DoubleProperty value is valid or not upon submit because it will only be valid when the submit button is enabled. Here is a simple example:

    
            
                
                    
                        
                    
                
            
        
    

    In the above example you need to define a class NumberValidationRule that inherits ValidationRule.

    Here is a sample NumberValidationRule

    public class NumberValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            double result = 0.0;
            bool canConvert = double.TryParse(value as string, out result);
            return new ValidationResult(canConvert, "Not a valid double");
        }
    }
    

    Once you add a validation rule the text box will raise an error on the text field if your ValidationRule class says its not a valid value.

    To prevent the submit button from being enabled you can add a CanExecute event to it that checks if the wpf window is valid. Like so:

    
        
    
    
    ... The rest of your page
    
    

    and in the code behind

    private void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = IsValid(sender as DependencyObject);
        }
    
    private bool IsValid(DependencyObject obj)
        {            
            return !Validation.GetHasError(obj) && LogicalTreeHelper.GetChildren(obj).OfType().All(IsValid);
        }
    

    Here is a more detailed example:

    Validation in WPF

提交回复
热议问题