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

前端 未结 3 977
悲哀的现实
悲哀的现实 2021-01-04 07:27

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

3条回答
  •  情深已故
    2021-01-04 08:02

    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.

提交回复
热议问题