Accessing WPF control validation rules from code

前端 未结 3 1664
长情又很酷
长情又很酷 2021-02-01 20:36

XAML:

  
      
          
              
                  <         


        
3条回答
  •  野的像风
    2021-02-01 21:21

    Validation.HasError is an attached property so you can check it for textboxMin like this

    void buttonOK_Click(object sender, RoutedEventArgs e)
    {
        if (Validation.GetHasError(textboxMin) == true)
             return;
    }
    

    To run all ValidationRules for the TextProperty in code behind you can get the BindingExpression and call UpdateSource

    BindingExpression be = textboxMin.GetBindingExpression(TextBox.TextProperty);
    be.UpdateSource();
    

    Update

    It will take some steps to achieve the binding to disable the button if any validation occurs.

    First, make sure all bindings add NotifyOnValidationError="True". Example

    
        
            
                
                    
                
            
        
    
    

    Then we hook up an EventHandler to the Validation.Error event in the Window.

    
    

    And in code behind we add and remove the validation errors in an observablecollection as they come and go

    public ObservableCollection ValidationErrors { get; private set; } 
    private void Window_Error(object sender, ValidationErrorEventArgs e)
    {
        if (e.Action == ValidationErrorEventAction.Added)
        {
            ValidationErrors.Add(e.Error);
        }
        else
        {
            ValidationErrors.Remove(e.Error);
        }
    }
    

    And then we can bind IsEnabled of the Button to ValidationErrors.Count like this

    
    

提交回复
热议问题