入力データ検証 その2 ErrorTemplate

前回のその1で紹介したサンプルでは、検証が不合格の際にTextBoxに対して赤い枠線が表示されるというUI上のフィードバックがありました。
その際にこれは既定のErrorTemplateであると説明しましたが、今回はこのErrorTemplateについて説明したいと思います。


検証が不合格の場合、Validation.ErrorTemplate添付プロパティに設定された内容が表示されます。ErrorTemplate添付プロパティはControlTemplate型ですので、表示させたいControlTemplateを作成しErrorTemplate添付プロパティに設定してあげれば良いわけです。


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" Text="{Binding ID, ValidatesOnExceptions=True}">
            <Validation.ErrorTemplate>
                <ControlTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock FontSize="{TemplateBinding FontSize}" Text="L" FontFamily="Wingdings"
                                          Foreground="Red" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        <AdornedElementPlaceholder/>
                    </StackPanel>
                </ControlTemplate>
            </Validation.ErrorTemplate>
        </TextBox>
 
        <Button Margin="30" Content="Focus to me."/>
    </StackPanel>
</Window>





ControlTemplateの中で重要なのはAdornedElementPlaceholderという要素で、この要素はErrorTemplateが適用される要素(ここではTextBox)を表します。


上記の例では直接ErrorTemplate添付プロパティに設定していますが、複数のコントロールに同じErrorTemplateを設定したい場合には当然ながらリソースとして定義すれば対応できます。


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>
        <ControlTemplate x:Key="ErrTmp">
            <StackPanel Orientation="Horizontal">
                <TextBlock FontSize="{TemplateBinding FontSize}" Text="L" FontFamily="Wingdings"
                                          Foreground="Red" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                <AdornedElementPlaceholder/>
            </StackPanel>
        </ControlTemplate>
    </Window.Resources>
    <StackPanel>
 
        <TextBox Margin="30" Text="{Binding ID, ValidatesOnExceptions=True}"
                Validation.ErrorTemplate="{StaticResource ErrTmp}"/>
 
        <TextBox Margin="30" Text="{Binding ID, ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}"
                Validation.ErrorTemplate="{StaticResource ErrTmp}"/>
    </StackPanel>
</Window>





検証結果のUI上のフィードバック方法はErrorTemplate以外にも方法が用意されています。その3ではそれをご紹介したいと思います。