Search code examples
.netwpfmvvmbindingvalidationrules

TextBox with Validation. How to update the target property even if the entered text is not valid?


I have a TextBox in my View, bound to a Property MyText in my ViewModel. I also have a ValidationRule for the input.

Here is the TextBox in my View:

<TextBox>
    <TextBox.Text>
        <Binding Path="MyText"
                 UpdateSourceTrigger="PropertyChanged" 
                 Mode="TwoWay"
                 ValidatesOnNotifyDataErrors="True"
                 ValidatesOnDataErrors="True"
                 NotifyOnValidationError="True">
            <Binding.ValidationRules>
                <local:FormulaValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

And here is my Validation class:

Public Class MyTextValidationRule
    Inherits ValidationRule

    Public Overrides Function Validate(value As Object, cultureInfo As CultureInfo) As ValidationResult

        Dim validationRes = MyParser.ValidateText(value)
        If validationRes Then
            Return ValidationResult.ValidResult
        Else
            Return New ValidationResult(False, "Input is not valid")
        End If
    End Function
End Class

What I want is that my property MyText gets updated, even if the entered Text is not valid, however, like what I have now, the property gets only updated if the text is valid. Is there any way to do it, i.e., update the property, or access the text of my TextBox?


Solution

  • Setting the ValidationStep property of a ValidationRule to UpdatedValue will cause it to be run after the source property has been updated:

    <Binding.ValidationRules>
        <local:FormulaValidationRule ValidationStep="UpdatedValue"  />
    </Binding.ValidationRules>
    

    The default value is RawProposedValue which means that the validation rule is run before the value conversion occurs and the source property is being set.