Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Validation: Clearing all validation errors

Tags:

validation

wpf

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?

like image 707
theSpyCry Avatar asked Jun 30 '10 09:06

theSpyCry


1 Answers

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.

like image 194
hbarck Avatar answered Sep 23 '22 14:09

hbarck