Binding.ValidatesOnExceptions Propriedade
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Obtém ou define um valor que indica se deve incluir o 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 Propriedade
true para incluir o ExceptionValidationRule; caso contrário, false.
Exemplos
Os exemplos seguintes são usados ValidatesOnExceptions para validar a entrada do utilizador num TextBox. O primeiro exemplo cria um tipo de dado que lança uma exceção quando a Age propriedade é definida como invá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
O exemplo seguinte liga a propriedade Age ao TextBox e define ValidatesOnExceptions a true no Binding. Quando o utilizador insere um valor inválido, aparece uma borda vermelha no TextBox e reporta ToolTip a mensagem de erro.
<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>
Observações
Definir esta propriedade oferece uma alternativa ao uso explícito do ExceptionValidationRule elemento. É ExceptionValidationRule uma regra de validação incorporada que verifica exceções lançadas durante a atualização da propriedade de origem. Se uma exceção for lançada, o motor de ligação cria a ValidationError com a exceção e adiciona-a à Validation.Errors coleção do elemento vinculado. A ausência de erro elimina este feedback de validação, a menos que outra regra levante uma questão de validação.
ValidatesOnExceptions é introduzido na versão 3.5 do .NET Framework. Para mais informações, verifique Versões e Dependências do .NET Framework.