WPF Validation: Clearing all validation errors

validationwpf

I have a WPF UserControl with many other controls inside of it.
TextBoxes are among these.
Every TextBox has its own validation:

<TextBox>
    <TextBox.Text>
        <Binding Path="MyPath" StringFormat="{}{0:N}" NotifyOnValidationError="True">
            <Binding.ValidationRules>
                <r:MyValidationRule ValidationType="decimal" />
            </Binding.ValidationRules>
        </Binding>
    <TextBox.Text>
<TextBox>

a

Now suppose the user types some invalid characters into them. They will all become highlighted red.

Now I want to reset all the validation errors (from the incorrect input) and set the recent correct values coming from DataContext.

I set the DataContext in the constructor and I don't want to change it (DataContext = null won't help me then):

DataContext = _myDataContext = new MyDataContext(..);

What I've already found are these classes:

Validation.ClearInvalid(..)
BindingExpression.UpdateTarget();

I think these classes could help me, but they require the Binding of a concrete FrameworkElement and I want to do it globally for all of them.

Should I anyhow iterate through the Visual Tree (which is really what I don't like) or is there any better solution for this?

Best Answer

This is what a BindingGroup is for... You'd set a BindingGroup on a container of all the controls, e.g. the panel that contains them. This would cause the updates to the DataContext to be held until you call UpdateSources on the BindingGroup. If you want to reset the user's input, you'd call CancelEdit instead, and the BindingGroup would reset all controls inside the container to the (still unchanged) values of the DataContext.

Related Topic