Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get WPF to NOT display validation errors upon initial display of control?

Tags:

validation

wpf

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);
    }
}
like image 441
Brian Sullivan Avatar asked May 12 '10 19:05

Brian Sullivan


1 Answers

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.

like image 143
Robert Rossney Avatar answered Oct 18 '22 20:10

Robert Rossney