Export (0) Print
Expand All
1 out of 2 rated this helpful - Rate this topic

Validation Class

Provides methods and attached properties that support data validation.

System.Object
  System.Windows.Controls.Validation

Namespace:  System.Windows.Controls
Assembly:  PresentationFramework (in PresentationFramework.dll)
public static class Validation

The Validation type exposes the following members.

  NameDescription
Public attached propertyErrorsGets the collection of all active ValidationError objects on the bound element.
Public attached propertyErrorTemplateGets or sets the ControlTemplate used to generate validation error feedback on the adorner layer.
Public attached propertyHasErrorGets a value that indicates whether any binding on the binding target element has a ValidationError.
Public attached propertyValidationAdornerSiteGets or sets the element that appears to indicate that a validation error occurred on the bound element where this property is set.
Public attached propertyValidationAdornerSiteForGets or sets the element for which this element appears to indicate that an error occurred.
Top
  NameDescription
Public methodStatic memberAddErrorHandlerAdds an event handler for the Error attached event to the specified object.
Public methodStatic memberClearInvalidRemoves all ValidationError objects from the specified BindingExpressionBase object.
Public methodStatic memberGetErrorsGets the value of the Errors attached property of the specified element.
Public methodStatic memberGetErrorTemplateGets the value of the ErrorTemplate attached property of the specified element.
Public methodStatic memberGetHasErrorGets the value of the HasError attached property of the specified element.
Public methodStatic memberGetValidationAdornerSiteGets the value of the ValidationAdornerSite attached property for the specified element.
Public methodStatic memberGetValidationAdornerSiteForGets the value of the ValidationAdornerSiteFor attached property for the specified element.
Public methodStatic memberMarkInvalidMarks the specified BindingExpression object as invalid with the specified ValidationError object.
Public methodStatic memberRemoveErrorHandlerAdds an event handler for the Error attached event from the specified object.
Public methodStatic memberSetErrorTemplateSets the value of the ErrorTemplate attached property to the specified element.
Public methodStatic memberSetValidationAdornerSiteSets the ValidationAdornerSite attached property to the specified value on the specified element.
Public methodStatic memberSetValidationAdornerSiteForSets the ValidationAdornerSiteFor attached property to the specified value on the specified element.
Top
  NameDescription
Public attached eventErrorOccurs when the bound element runs into a validation error, but only for bindings with the NotifyOnValidationError value set to true.
Top
  NameDescription
Public fieldStatic memberErrorEventIdentifies the Error attached event.
Public fieldStatic memberErrorsPropertyIdentifies the Errors attached property.
Public fieldStatic memberErrorTemplatePropertyIdentifies the ErrorTemplate attached property.
Public fieldStatic memberHasErrorPropertyIdentifies the HasError attached property.
Public fieldStatic memberValidationAdornerSiteForPropertyIdentifies the ValidationAdornerSiteFor attached property.
Public fieldStatic memberValidationAdornerSitePropertyIdentifies the ValidationAdornerSite attached property.
Top

For a detailed discussion of the validation process, see "Data Validation" in Data Binding Overview.

This example shows how to use an ErrorTemplate and a style trigger to provide visual feedback to inform the user when an invalid value is entered, based on a custom validation rule.

The text content of the TextBox in the following example is bound to the Age property (of type int) of a binding source object named ods. The binding is set up to use a validation rule named AgeRangeRule so that if the user enters non-numeric characters or a value that is smaller than 21 or greater than 130, a red exclamation mark appears next to the text box and a tool tip with the error message appears when the user moves the mouse over the text box.


<TextBox Name="textBox1" Width="50" FontSize="15"
         Validation.ErrorTemplate="{StaticResource validationTemplate}"
         Style="{StaticResource textBoxInError}"
         Grid.Row="1" Grid.Column="1" Margin="2">
  <TextBox.Text>
    <Binding Path="Age" Source="{StaticResource ods}"
             UpdateSourceTrigger="PropertyChanged" >
      <Binding.ValidationRules>
        <c:AgeRangeRule Min="21" Max="130"/>
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
</TextBox>


The following example shows the implementation of AgeRangeRule, which inherits from ValidationRule and overrides the Validate method. The Int32.Parse() method is called on the value to make sure that it does not contain any invalid characters. The Validate method returns a ValidationResult that indicates if the value is valid based on whether an exception is caught during the parsing and whether the age value is outside of the lower and upper bounds.


public class AgeRangeRule : ValidationRule
{
    private int _min;
    private int _max;

    public AgeRangeRule()
    {
    }

    public int Min
    {
        get { return _min; }
        set { _min = value; }
    }

    public int Max
    {
        get { return _max; }
        set { _max = value; }
    }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        int age = 0;

        try
        {
            if (((string)value).Length > 0)
                age = Int32.Parse((String)value);
        }
        catch (Exception e)
        {
            return new ValidationResult(false, "Illegal characters or " + e.Message);
        }

        if ((age < Min) || (age > Max))
        {
            return new ValidationResult(false,
              "Please enter an age in the range: " + Min + " - " + Max + ".");
        }
        else
        {
            return new ValidationResult(true, null);
        }
    }
}


The following example shows the custom ControlTemplate validationTemplate that creates a red exclamation mark to notify the user of a validation error. Control templates are used to redefine the appearance of a control.


<ControlTemplate x:Key="validationTemplate">
  <DockPanel>
    <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
    <AdornedElementPlaceholder/>
  </DockPanel>
</ControlTemplate>


As shown in the following example, the ToolTip that shows the error message is created using the style named textBoxInError. If the value of HasError is true, the trigger sets the tool tip of the current TextBox to its first validation error. The RelativeSource is set to Self, referring to the current element.


<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
  <Style.Triggers>
    <Trigger Property="Validation.HasError" Value="true">
      <Setter Property="ToolTip"
        Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)[0].ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
</Style>


For the complete example, see Binding Validation Sample.

Note that if you do not provide a custom ErrorTemplate the default error template appears to provide visual feedback to the user when there is a validation error. See "Data Validation" in Data Binding Overview for more information. Also, WPF provides a built-in validation rule that catches exceptions that are thrown during the update of the binding source property. For more information, see ExceptionValidationRule.

.NET Framework

Supported in: 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

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.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.