ValidationRule.ValidatesOnTargetUpdated Property
Gets or sets a value that indicates whether the validation rule runs when the target of the Binding is updated.
Assembly: PresentationFramework (in PresentationFramework.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation, http://schemas.microsoft.com/netfx/2007/xaml/presentation
<object ValidatesOnTargetUpdated="bool" .../>
Property Value
Type: System.Booleantrue if the validation rule runs when the target of the Binding is updated; otherwise, false.
The following example checks whether the TextBox is empty. The ValidationRule, ValueIsNotNull, has ValidatesOnTargetUpdated set to true, so that when the application starts, the ValidationRule runs and displays a message if the TextBox is empty.
<TextBox Width="150" Validation.Error="ItemError"> <TextBox.Text> <Binding Source="{StaticResource myObject}" Path="PropertyB" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True"> <Binding.ValidationRules> <src:ValueIsNotNull ValidatesOnTargetUpdated="True" /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox>
The following example shows the ValidationRule that is used in the previous example and the event handler for the Error event.
public class ValueIsNotNull : ValidationRule { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { string str = value as string; if (!string.IsNullOrEmpty(str)) { return ValidationResult.ValidResult; } else { return new ValidationResult(false, "Value must not be null"); } } }
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
From WPFGlue:
Problem: The Error Template is not Displayed when a Page is Loaded
This is by design, since one could assume that the user doesn’t want to see error messages before he/she made any mistakes, but sometimes one needs this functionality. So, the ValidatesOnTargetUpdated property was introduced on the ValidationRule class; by setting it to true, one sees the validation result immediately.
However, there is one caveat: you must make sure that you set the DataContext after the page is initialized; this would be either in the constructor after the generated comment line that says that initialization code should go there, or in the Loaded event. If you want to set the DataContext in XAML, you find a solution for this problem here (among other things): http://wpfglue.wordpress.com/2009/12/08/navigating-from-object-to-object/
- 5/9/2011
- Drammy