tags:

views:

102

answers:

2

When I first display my screen to the user, I'd rather not have all the validation messages show up for required fields and such before the user has had a chance to fill in any of the form fields. I've set the UpdateSourceTrigger on my bindings to LostFocus, but the errors are still displayed the first time the control is shown. Is there any way to get around this?

XAML:

<TextBox Text="{Binding Path=OpeningOdometer, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" />

ViewModel:

[Required(ErrorMessage = "Please enter the opening odometer.")]
[Range(0, Double.MaxValue, ErrorMessage = "Opening Odometer must be a positive number")]        
public string OpeningOdometer
{
    get { return _openingOdometer; }
    set
    {
        _openingOdometer = value;
        NotifyOfPropertyChange(() => OpeningOdometer);
    }
}

// Implementation of IDataErrorInfo
public string this[string columnName]
{
    get
    {
        // This uses the System.ComponentModel.DataAnnotations placed on
        // the OpeningOdometer property to produce an error string
        // if the value of the property is in violation of any of the 
        // annotated rules.
        return _valHelper.GetErrorsForProperty(columnName, this);
    }
}
+1  A: 

You can get better answers if you make an effort to post a snippet of your relevant code/XAML. It would make it easier to reproduce and eliminate much of the guesswork.

Try setting ValidatesOnTargetUpdated="False" on your validation rules and see if that helps.

wpfwannabe
I'm actually not using ValidationRules, I'm implementing IDataErrorInfo. Should have included more detail in the question, apologies.
Brian Sullivan
+1  A: 

I don't put validation logic in the indexer. That turns control over the timing of validation to the view. In your scheme, the view triggers validation whenever it asks for the property's error info. I don't know every circumstance in which that's going to happen and I bet you don't either.

Instead, I put a property's validation logic (more accurately, the call to the validation function) in its setter. I store the error message in a dictionary keyed on property name, and have the indexer look up the error message for the property.

By default, then, the error message is up to date with the property's current value. Whenever the view updates a property and requests its new error info, it'll get the right answer.

But you also have pretty fine-grained control over what's actually in that dictionary. If you want a property to show up in the UI as valid, just clear its error message in the dictionary (and raise PropertyChanged, so the UI will know to get the new error message). Or you can set the properties' backing fields instead of the properties themselves, bypassing validation, when you construct the view model object.

Robert Rossney