入力データ検証 その4 Error添付イベント
前回のその3ではHasError添付プロパティとプロパティトリガを利用したデータ検証におけるUI上のフィードバック方法をご紹介しました。最後のUI上のフィードバック方法として、今回はError添付イベントをご紹介します。
BindingクラスのNotifyOnValidationErrorプロパティをTrueに設定することで、バインドしている要素のValidation.Errors添付プロパティの値が変化した際にError添付イベントをハンドルできるようになります。
Error添付イベントのコールバック内でValidationErrorEventArgs.Actionプロパティを使って検証の不合格を判定することで、UI上のフィードバックを実現することが可能です。XAMLだけでは実現が不可能な場合にこの方法を利用すると良いかもしれません。
Window1.xaml
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" FontSize="32">
<StackPanel>
<TextBox Margin="30" Validation.Error="TextBox_Error"
Text="{Binding ID, ValidatesOnExceptions=True, NotifyOnValidationError=True,
UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
</Window>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" FontSize="32">
<StackPanel>
<TextBox Margin="30" Validation.Error="TextBox_Error"
Text="{Binding ID, ValidatesOnExceptions=True, NotifyOnValidationError=True,
UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
</Window>
Window1.xaml.vb
Class Window1
Sub New()
' この呼び出しは、Windows フォーム デザイナで必要です。
InitializeComponent()
' InitializeComponent() 呼び出しの後で初期化を追加します。
Me.DataContext = New DataSource()
End Sub
Private Sub TextBox_Error(ByVal sender As System.Object, ByVal e As System.Windows.Controls.ValidationErrorEventArgs)
Dim target As TextBox
target = TryCast(e.OriginalSource, TextBox)
If Not target Is Nothing Then
Select Case (e.Action)
Case ValidationErrorEventAction.Added
target.SelectAll()
Case ValidationErrorEventAction.Removed
End Select
End If
End Sub
End Class
Sub New()
' この呼び出しは、Windows フォーム デザイナで必要です。
InitializeComponent()
' InitializeComponent() 呼び出しの後で初期化を追加します。
Me.DataContext = New DataSource()
End Sub
Private Sub TextBox_Error(ByVal sender As System.Object, ByVal e As System.Windows.Controls.ValidationErrorEventArgs)
Dim target As TextBox
target = TryCast(e.OriginalSource, TextBox)
If Not target Is Nothing Then
Select Case (e.Action)
Case ValidationErrorEventAction.Added
target.SelectAll()
Case ValidationErrorEventAction.Removed
End Select
End If
End Sub
End Class
その2からその4にかけて3つのUI上のフィードバック方法をご紹介してきました。少々順序が逆なような気がしましたが、次回からはカスタムの検証ルールを実現する方法についてご紹介していきたいと思います。