方法: バインディングの検証の実装

この例では、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

次の例では、検証エラーをユーザーに通知する赤い感嘆符を作成するための、カスタム ControlTemplatevalidationTemplate を示します。 コントロール テンプレートは、コントロールの外観を再定義するために使用されます。

<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」を参照してください。

関連項目