Binding.ValidatesOnExceptions 屬性

定義

取得或設定一個值,指示是否包含 。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

屬性值

true 包含 ExceptionValidationRule;否則, false

範例

以下範例用ValidatesOnExceptions來驗證使用者輸入。TextBox 第一個範例會產生一個資料型別,當屬性 Age 被設定為無效屬性時,會拋出例外。

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

以下範例將屬性 Age 綁定於 , TextBox 並設定 ValidatesOnExceptionstrueBinding。 當使用者輸入無效值時,會出現紅色邊框 TextBox ,並回報 ToolTip 錯誤訊息。

<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>

備註

設定此屬性提供一種明確使用元素 ExceptionValidationRule 的替代方案。 這是 ExceptionValidationRule 一條內建的驗證規則,用來檢查在更新原始屬性時拋出的異常。 若拋出例外,綁定引擎會建立包含該例外的 a ValidationError ,並將其加入 Validation.Errors 綁定元素的集合中。 沒有錯誤即可消除此驗證回饋,除非其他規則提出驗證問題。

ValidatesOnExceptions 於 .NET Framework 3.5 版本中引入。 如需詳細資訊,請參閱 .NET Framework 版本和相依性

適用於

另請參閱