Yvonnila
Yvonnila

Reputation: 646

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?

Upvotes: 2

Views: 1019

Answers (2)

mm8
mm8

Reputation: 169210

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.

Upvotes: 2

Coops
Coops

Reputation: 301

What you can do if you want to show a visible indicator that the input is wrong but still keep a record of it is to use ValidatesOnExceptions, the following article gives a good explanation of it all: Data Validation in WPF

It's kind of meant for if there is a conversion error to the backing property, but there is nothing stopping you taking the value in to the field of the ViewModel in the property setter then performing the parsing and throwing an Exception as desired. That way you'll have a copy of the value set but also the UI showing that there is an error.

Upvotes: 0

Related Questions