次の方法で共有


方法: バインド検証を実装する

この例では、 ErrorTemplate とスタイル トリガーを使用して、カスタム検証規則に基づいて無効な値が入力されたときにユーザーに通知する視覚的フィードバックを提供する方法を示します。

次の例のTextBoxのテキスト コンテンツは、Age という名前のバインディング ソース オブジェクトの ods プロパティ (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>
        <local: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 override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        int age = 0;

        try
        {
            if (((string)value).Length > 0)
                age = int.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)[0].ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
</Style>

データ オブジェクト

次のスニペットは、前のコード例で使用したデータ オブジェクトです。 インスタンスは、 odsのキーを持つ静的リソースとして XAML で作成されます。

public class MyDataSource
{
    public MyDataSource()
    {
        Age = 0;
        Age2 = 0;
    }

    public int Age { get; set; }
    public int Age2 { get; set; }
    public int Age3 { get; set; }
}
Public Class MyDataSource
    Public Sub New()
        Me.Age = 0
        Me.Age2 = 0
    End Sub

    Public Property Age As Integer
    Public Property Age2 As Integer
    Public Property Age3 As Integer
End Class

完全な例

完全な例については、 バインド検証のサンプルを参照してください。

カスタム ErrorTemplate を指定しない場合、検証エラーが発生したときに、既定のエラー テンプレートがユーザーに視覚的なフィードバックを提供するように見える点に注意してください。 詳細については、「データ バインディングの 概要 」の「データ検証」を参照してください。 また、WPF には、バインディング ソース プロパティの更新中にスローされる例外をキャッチする組み込みの検証規則が用意されています。 詳細については、ExceptionValidationRuleを参照してください。

こちらも参照ください