Setting Validation error template from code in WPF

前端 未结 4 1284
醉话见心
醉话见心 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 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
    

提交回复
热议问题