WPF アプリケーションでは、バインディングの機能を使用してデータ検証を行うことができます。入力検証ではバインディングされる各プロパティの Setter でチェック処理を行い、例外をスローするように実装します。
検証インジケータコントロールは、指定されたコントロールにて発生した例外をキャッチし、エラーアイコンを点滅表示することでエラーが発生したことを通知します。エラーアイコン上のマウスを移動することで、エラーの内容をツールチップで表示します。
検証インジケータコントロールの ElementName プロパティに、検証対象となるコントロールの Name プロパティまたは x:Name Attribute 属性の値を設定することで、検証インジケータコントロールは指定されたコントロールを監視し、検証が行われた際にその結果を表示するようになります。
以下のサンプルコードは、DataErrorValidationRule を使用して検証を行い、検証インジケータコントロールによって TextBox コントロールを監視し、値が空の場合は入力エラーとしてエラーアイコンを表示します。
Imports System.ComponentModel
' 以下の1行は、MainWindow のコンストラクタ内に記述してください。
Me.DataContext = New SampleData()
Public Class SampleData
Implements IDataErrorInfo
Public Property Address As String
Public ReadOnly Property [Error] As String Implements IDataErrorInfo.Error
Get
Return Nothing
End Get
End Property
Default Public ReadOnly Property Item(ByVal columnName As String) As String Implements IDataErrorInfo.Item
Get
If columnName = "Address" Then
If String.IsNullOrEmpty(Me.Address) Then
Return "入力必須項目です"
End If
End If
Return Nothing
End Get
End Property
End Class
using System.ComponentModel;
using System.Windows;
// 以下の1行は、MainWindow のコンストラクタ内に記述してください。
this.DataContext = new SampleData();
public class SampleData : IDataErrorInfo
{
public string Address { get; set; }
public string Error
{
get { return null; }
}
public string this[string columnName]
{
get
{
if (columnName == "Address")
if (string.IsNullOrEmpty(this.Address))
return "入力必須項目です";
return null;
}
}
}
<!-- VB、C#とも、以下のコードをページ内に記述してください -->
<StackPanel Orientation="Horizontal" Width="250" Height="25">
<TextBlock Text="住所" VerticalAlignment="Center" />
<TextBox x:Name="address" Width="150">
<TextBox.Text>
<Binding Path="Address">
<Binding.ValidationRules>
<DataErrorValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<im:GcValidationIndicator x:Name="errorIcon" ElementName="address" Width="16" Height="16" />
<Button Margin="20, 0" Content="登録" />
</StackPanel>
また、以下のサンプルコードは、DataAnnotations を使用して検証を行い、検証インジケータコントロールによって TextBox コントロールを監視し、値が空の場合は入力エラーとしてエラーアイコンを表示します。
 |
このサンプルコードを実行する際は、「デバッグ無しで開始」([Ctrl]+[F5])を選択してください。 |
' 参照設定にて System.ComponentModel.DataAnnotations.dll アセンブリへの参照を追加してください。
Imports System.ComponentModel.DataAnnotations
' 以下の1行は、MainWindow のコンストラクタ内に記述してください。
Me.DataContext = New SampleData()
Public Class SampleData
Private _address As String
<Required(ErrorMessage:="入力必須項目です")>
Public Property Address As String
Get
Return Me._address
End Get
Set(ByVal value As String)
Validator.ValidateProperty(value, New ValidationContext(Me, Nothing, Nothing) With {.MemberName = "Address"})
_address = value
End Set
End Property
End Class
// 参照設定にて System.ComponentModel.DataAnnotations.dll アセンブリへの参照を追加してください。
using System.ComponentModel.DataAnnotations;
// 以下の1行は、MainWindow のコンストラクタ内に記述してください。
this.DataContext = new SampleData();
public class SampleData
{
private string _address;
[Required(ErrorMessage = "入力必須項目です")]
public string Address
{
get { return _address; }
set
{
Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Address" });
_address = value;
}
}
}
<!-- VB、C#とも、以下のコードをページ内に記述してください -->
<StackPanel Orientation="Horizontal" Width="250" Height="25">
<TextBlock Text="住所" VerticalAlignment="Center" />
<TextBox x:Name="address" Width="150">
<TextBox.Text>
<Binding Path="Address" ValidatesOnExceptions="True" NotifyOnValidationError="True"/>
</TextBox.Text>
</TextBox>
<im:GcValidationIndicator x:Name="errorIcon" ElementName="address" Width="16" Height="16" />
<Button Margin="20, 0" Content="登録" />
</StackPanel>
エラーアイコンを表示する際は、BlinkStyle プロパティの設定に基づいて点滅表示が行われます。BlinkStyle.AlwaysBlink のときは、常に点滅表示となります。BlinkStyle.BlinkOnValidate のときは、数回点滅した後点灯状態となります。BlinkStyle.NeverBlink のときは、点滅表示は行わず、常に点灯状態となります。
また、BlinkRate プロパティを使って点滅の速度をミリ秒単位で指定できます。BlinkRate プロパティに 0 を設定した場合は、BlinkStyle プロパティが BlinkStyle.NeverBlink に設定され、点滅表示は行われなくなります。
MarkError メソッドは、既存のすべての検証エラーを削除し、指定されたエラー内容でエラーアイコンを表示します。また、ClearError メソッドは、既存のすべての検証エラーを削除します。これらのメソッドを使用することで、検証インジケータによるエラー通知のタイミングを任意に制御することができます。
以下のサンプルコードは、テキストボックスに文字が入力されるたびに検証を行い、その結果に基づいてエラーアイコンを表示あるいは非表示にします。
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
If (String.IsNullOrWhiteSpace(TextBox1.Text)) Then
GcValidationIndicator1.MarkError(New TextBlock() With {.Text = "入力必須項目です。", .Foreground = New SolidColorBrush(Colors.Red)})
ElseIf (TextBox1.Text.Length > 10) Then
GcValidationIndicator1.MarkError(New TextBlock() With {.Text = "10文字以内で入力してください。", .Foreground = New SolidColorBrush(Colors.Green)})
Else
GcValidationIndicator1.ClearError()
End If
End Sub
private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (string.IsNullOrWhiteSpace(TextBox1.Text))
GcValidationIndicator1.MarkError(new TextBlock() { Text = "入力必須項目です。", Foreground = new SolidColorBrush(Colors.Red) });
else if (TextBox1.Text.Length > 10)
GcValidationIndicator1.MarkError(new TextBlock() { Text = "10文字以内で入力してください。", Foreground = new SolidColorBrush(Colors.Green) });
else
GcValidationIndicator1.ClearError();
}
<!-- VB、C#とも、以下のコードをページ内に記述してください -->
<StackPanel Orientation="Horizontal" Height="23">
<TextBlock Text="氏名:" VerticalAlignment="Center" />
<TextBox Name="TextBox1" Width="120" TextChanged="TextBox1_TextChanged" />
<im:GcValidationIndicator Name="GcValidationIndicator1" Width="16" Height="16" ElementName="TextBox1" />
</StackPanel>