Scott Baker
Scott Baker

Reputation: 10443

Doing all my validation in the ViewModel

How can I stop the UI layer from performing its conversion validation, or at least have it continue on? If I have a textbox bound to a DateTime:

// view
<TextBox x:Name="StartTimeTextBox">
        <TextBox.Text>
            <Binding Path="StartTime"
                     StringFormat="t"
                     NotifyOnValidationError="True" 
                     ValidatesOnDataErrors="True" 
                     ValidatesOnExceptions="True" >
                <Binding.ValidationRules>
                    <va:AlwaysSucceedsValidationRule/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

// view model
[MyValidationAttribute]
public DateTime StartTime {get; set;}

When the user selects all the text text in the textbox and deletes it (or types in "asdf"), the conversion fails, it gets a red border and validation stops. I've tried using ValidatesOn... attributes (which I thought would allow my "MyValidationAttribute" to execute) without success. I've also tried adding a ValidationRule that always returns true no matter what the Text - but nothing works.

Upvotes: 0

Views: 54

Answers (1)

If you bind TextBox.Text to a DateTime, and the user types in "my hovercraft is full of little lambs", what can the Binding possibly assign to your viewmodel property for you to validate? There's nothing it can do.

You can set Validation.ErrorTemplate for the TextBox to an empty template, and that'll get rid of the red outline business, but you still won't get anything validatable in your viewmodel property.

If you want to validate string input from the user as a valid or invalid date, you're going to have to do that at some point where you have the raw string input in your hands.

If you want to do it in your viewmodel, that means giving your viewmodel a string property for StartTime, and binding that to the TextBox. Call it StringStartTime; in its setter, if the string is valid it sets DateTime StartTime; if not valid, it leaves StartTime alone but sets some error property, or throws an exception, or whatever.

Upvotes: 1

Related Questions