入力データ検証 その3 HasError添付プロパティ
その2では、ErrorTemplateを使ったUI上のフィードバックを取り上げましたが、今回はValidation.HasError添付プロパティを使った方法をご紹介します。
HasError添付プロパティは検証が不合格になった場合に、つまりValidation.Errors添付プロパティに何らかのValidationErrorが追加されているときに、Trueを返すプロパティです。
プロパティトリガを使ってHasError添付プロパティが変更された時のアクションを記述することで、UI上のフィードバックを実現することができます。
下記のサンプルはMSDNのサンプルにも記載されているものと同様で、検証が不合格の場合にエラーの内容をToolTipに表示するというものです。
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">
<Window.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<TextBox Margin="30" Text="{Binding ID, ValidatesOnExceptions=True}"/>
<Button Margin="30" Content="Focus to me."/>
</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">
<Window.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<TextBox Margin="30" Text="{Binding ID, ValidatesOnExceptions=True}"/>
<Button Margin="30" Content="Focus to me."/>
</StackPanel>
</Window>
SetterのValueのバインド先は、自分自身のErrors添付プロパティに設定されている最初のValidationErrorのErrorContentプロパティになります。Exceptionによるエラーの場合、ErrorContentプロパティにはExceptionの説明が入りますので、ここでは「入力文字列の形式が正しくありません。」という内容がToolTipに表示されています。
それに加え、BackgorundプロパティとForegroundプロパティも変更し、背景と文字の色が変更されるようにしています。
短いですがその3はこれでおしまいです。その4ではさらにもう一つのUI上のフィードバック方法をご紹介したいと思います。