共用方式為


操作說明:實作繫結驗證

本範例顯示如何使用 ErrorTemplate 和樣式觸發程序,以提供視覺化回應,依據自訂驗證規則在輸入無效值時通知使用者。

範例

下列範例中 TextBox 的文字內容,是繫結到名為 ods 的繫結來源物件的 Age 屬性 (型別 int)。 繫結是設為使用名為 AgeRangeRule 的驗證規則,因此如果使用者輸入非數值字元或小於 21 或大於 130 的值,文字方塊旁邊會出現紅色驚嘆號,並在使用者移動滑鼠到文字方塊上方時出現具有錯誤訊息的工具提示。

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

下列範例示範 AgeRangeRule 的實作,其繼承自 ValidationRule 並覆寫 Validate 方法。 會對值呼叫 Int32.Parse 方法,以確保該值不包含任何無效的字元。 Validate 方法傳回的 ValidationResult 會依據剖析期間是否有攔截到例外狀況,以及年齡值是否超出上下限,以指出值是否有效。

public class AgeRangeRule : ValidationRule
{
    public int Min { get; set; }
    public int Max { get; set; }

    public AgeRangeRule()
    {
    }

    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}.");
        }
        return ValidationResult.ValidResult;
    }
}
Public Class AgeRangeRule
    Inherits ValidationRule

    ' Properties
    Public Property Max As Integer
    Public Property Min As Integer
        
    ' Methods
    Public Overrides Function Validate(value As Object, cultureInfo As CultureInfo) As ValidationResult
        Dim num1 As Integer = 0
        Try 
            If (CStr(value).Length > 0) Then
                num1 = Integer.Parse(CStr(value))
            End If
        Catch exception1 As Exception
            Return New ValidationResult(False, $"Illegal characters or {exception1.Message}")
        End Try
        If ((num1 < Min) OrElse (num1 > Max)) Then
            Return New ValidationResult(False, $"Please enter an age in the range: {Min}-{Max}.")
        End If
        Return ValidationResult.ValidResult
    End Function

End Class

下列範例顯示的自訂 ControlTemplate validationTemplate 會建立紅色驚嘆號,以通知使用者發生驗證錯誤。 控制項樣板是用於重新定義控制項的外觀。

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

如下列範例所示,顯示錯誤訊息的 ToolTip 是使用名為 textBoxInError 的樣式所建立。 如果 HasError 的值是 true,則觸發程序會將目前 TextBox 的工具提示設定為其第一個驗證錯誤。 RelativeSource 會設定為 Self,參考目前的元素。

<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)/ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
</Style>

如需完整範例,請參閱繫結驗證範例 (英文)

請注意,如果您沒有提供自訂 ErrorTemplate,就會在發生驗證錯誤時出現預設錯誤範本,以提供使用者視覺化的回應。 如需詳細資訊,請參閱資料繫結概觀中的<資料驗證>。 此外,WPF 提供的內建驗證規則,會攔截繫結來源屬性更新期間所擲回的例外狀況。 如需詳細資訊,請參閱ExceptionValidationRule

另請參閱