Setting Validation error template from code in WPF

前端 未结 4 1282
醉话见心
醉话见心 2021-02-13 22:40

I have a TextBox in my WPF app. I have defined a ControlTemplate for validation error as follows:


    

        
相关标签:
4条回答
  • 2021-02-13 22:51
    Validation.SetErrorTemplate(txtBox, this.FindResource("validationTemplate") as ControlTemplate);
    
    0 讨论(0)
  • 2021-02-13 22:53

    For your first question. You can set the ErrorTemplate from code behind like.

        public MainWindow()
        {
            InitializeComponent();
    
            var template = this.FindResource("validationTemplate") as ControlTemplate;
            Validation.SetErrorTemplate(this.textBox1, template);
         }
    


    Edit: For your second question. Please refer the following sample. sites.google.com/site/html5tutorials/ValidationErrorText.zip

    0 讨论(0)
  • 2021-02-13 23:01

    Thanks to for the wonderful link he suggested me.My code goes somewhat this way

    String errorMessage = GetFormattedErrorMessage(toolTip.Range, range);
    ValidationError validationError = new ValidationError(new DummyValidator(),
    txtBox.GetBindingExpression(TextBox.TextProperty));
    Validation.MarkInvalid(txtBox.GetBindingExpression(TextBox.TextProperty), validationError);
    validationError.ErrorContent = errorMessage;
    Validation.SetErrorTemplate(txtBox, GetErrorTemplate(errorMessage));
    
    0 讨论(0)
  • 2021-02-13 23:12

    To set "Validation.HasError" in code behind you can use the Validation.MarkInvalid method

    private void blockTextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) 
    { 
        TextBox txtBox = sender as TextBox;
        //...
        BindingExpression bindingExpression =
            BindingOperations.GetBindingExpression(txtBox, TextBox.TextProperty);
    
        BindingExpressionBase bindingExpressionBase = 
            BindingOperations.GetBindingExpressionBase(txtBox, TextBox.TextProperty);
    
        ValidationError validationError =
            new ValidationError(new ExceptionValidationRule(), bindingExpression);
    
        Validation.MarkInvalid(bindingExpressionBase, validationError);
    }
    

    To unset the value you use

    Validation.ClearInvalid
    
    0 讨论(0)
提交回复
热议问题