Binding errors occur when a noncritical exception is raised after the ConvertBack
method of the ValueConverter
is called. The following is a list of the three types of binding errors that can occur when modifying the value of a target property:
The user enters a value that fails to be converted to the source binding type (syntactic validation).
An exception is raised within the property set accessor.
The property does not have a set accessor and is, therefore, read-only.
Note
When a binding error occurs, the target, a TextBox
, for example, retains the entered value, but the source property is not updated.
By default, the XAML data-binding infrastructure fails silently when a binding error occurs. The NotifyOnValidationError
and the ValidatesOnExceptions
binding properties allow you to provide the user with feedback when a value is incorrectly set.
With the Binding.NotifyOnValidationError
property set to true, the data binding system raises a BindingValidationError
event when a binding error occurs. The following example demonstrates enabling validation on a TextBox
element:
<TextBox Text="{Binding ValidatedString2, Mode=TwoWay,
NotifyOnValidationError=True, ValidatesOnExceptions=True}"
Style="{StaticResource ValidatingTextBoxStyle}" />
The BindingValidationError
is a RoutedEvent
, allowing it to be handled by an ancestor element in the visual tree. RoutedEvents
bubble upward through the visual tree until they are either handled, indicated by the Handled
property of the event arguments, or they reach the root element of the visual tree. Subscription to the BindingValidationError
event at the page level, therefore, provides the opportunity to handle validation errors for all elements in the page. We leverage this later in the chapter to create a validation summary control.
The Binding
class’s NotifyOnValidationError
property works in unison with its ValidatesOnExceptions
property. If the ValidatesOnExceptions
property is not explicitly set to true and a binding error results from a noncritical exception being raised from a property accessor, the error is silently ignored. Furthermore, the VisualState
of the FrameworkElement
is not changed, and the BindingValidationError
event is not raised.
3.147.77.250