I have validation hooked up to a model that is bound to the TextBox
container. When the window is first opened validation errors appear as the model is empty, I do not want to see validation errors until submit of the window or the text in the TextBox
has changed or on lost focus.
Here is the TextBox
:
<TextBox Text="{Binding
Path=Firstname,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"
Width="124"
Height="24"/>
How can this be achieved?
This really depends on your implementation of IDataErrorInfo. If you base it around a Dictionary of error messages you can control when validation runs that adds to that list. You would normally want to do that from your property setters (like whenever you call PropertyChange), here calling CheckValidationState:
You can then also include a method that validates all of your properties (like during a save):
UPDATE:
I would recommend putting the above code into a base ViewModel class so you can reuse it. You could then create a derived class like this:
In this case I'm using a DelegateCommand to trigger the save operation but it could be anything that makes a method call to do the saving. This setup allows for the initial empty state to show up as valid in the UI but either a change or a call to Save updates the validation state. You can also get a lot more general and more complicated in the way you actually do the validation so it doesn't all end up in one method (here with some assumptions about the type) but this is simplified to make it easier to start with.
If you are implementing IDataErrorInfo, I've achieved this by checking for null values in the implementation of the validation logic. When creating a new window, checking for null will prevent your validation logic from firing. For example:
Also, if you want to fire the validation on TextBox.LostFocus, change your binding to LostFocus, like follows:
in your app.xaml file, you need to use custom textbox style for textbox validation without any third party component.
What I do, I donno if this is the correct way (I would be glad to learn, now is a chance), but in the initializer of the entity or the model I run all the validators.