Binding.ValidatesOnExceptions Propiedad

Definición

Obtiene o establece un valor que indica si se va a incluir el objeto ExceptionValidationRule.

public:
 property bool ValidatesOnExceptions { bool get(); void set(bool value); };
public bool ValidatesOnExceptions { get; set; }
member this.ValidatesOnExceptions : bool with get, set
Public Property ValidatesOnExceptions As Boolean

Valor de propiedad

Es true si se va a incluir el objeto ExceptionValidationRule; de lo contrario, es false.

Ejemplos

En los ejemplos siguientes se usa ValidatesOnExceptions para validar la entrada del usuario en .TextBox En el primer ejemplo se crea un tipo de datos que produce una excepción cuando la Age propiedad se establece en una propiedad no válida.

public class PersonThrowException
{
    private int age;

    public int Age
    {
        get { return age; }
        set
        {

            if (value < 0 || value > 150)
            {
                throw new ArgumentException("Age must not be less than 0 or greater than 150.");
            }
            age = value;
        }
    }
}
Public Class PersonThrowException
    Private m_age As Integer

    Public Property Age() As Integer
        Get
            Return m_age
        End Get
        Set(ByVal value As Integer)

            If value < 0 OrElse value > 150 Then
                Throw New ArgumentException("Age must not be less than 0 or greater than 150.")
            End If
            m_age = value
        End Set
    End Property
End Class

En el ejemplo siguiente se enlaza la Age propiedad a TextBox y se establece trueValidatesOnExceptions en en .Binding Cuando el usuario escribe un valor no válido, aparece un borde rojo en TextBox y ToolTip notifica el mensaje de error.

<StackPanel Margin="20">
  <StackPanel.Resources>
    
    <src:PersonThrowException x:Key="data"/>
    
    <!--The tool tip for the TextBox to display the validation error message.-->
    <Style x:Key="textBoxInError" TargetType="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>

  </StackPanel.Resources>
  <TextBlock>Enter your age:</TextBlock>
  <TextBox Style="{StaticResource textBoxInError}">
    <TextBox.Text>
      <!--By setting ValidatesOnExceptions to True, it checks for exceptions
        that are thrown during the update of the source property.
        An alternative syntax is to add <ExceptionValidationRule/> within
        the <Binding.ValidationRules> section.-->
      <Binding Path="Age" Source="{StaticResource data}"
               ValidatesOnExceptions="True"
               UpdateSourceTrigger="PropertyChanged">
      </Binding>
    </TextBox.Text>
  </TextBox>
  <TextBlock>Mouse-over to see the validation error message.</TextBlock>
</StackPanel>

Comentarios

Establecer esta propiedad proporciona una alternativa al uso del ExceptionValidationRule elemento explícitamente. ExceptionValidationRule es una regla de validación integrada que comprueba si hay excepciones que se producen durante la actualización de la propiedad de origen. Si se produce una excepción, el motor de enlace crea con ValidationError la excepción y lo agrega a la Validation.Errors colección del elemento enlazado. La falta de un error borra estos comentarios de validación, a menos que otra regla genere un problema de validación.

ValidatesOnExceptions se presenta en la versión 3.5 de .NET Framework. Para más información, consulte Versiones y dependencias de .NET Framework.

Se aplica a

Consulte también