入力された値を検証する

はじめに

ValidationRule を自作して、TextBox に入力された値を検証してみました。

ルールを作成

public class SuzukiValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        string text = value as string;
        if (text == null)
        {
            return new ValidationResult(false, "文字列じゃないよ!!");
        }

        if (text.StartsWith("鈴木") == false)
        {
            return new ValidationResult(false, "苗字が鈴木じゃないよ!!");
        }

        return new ValidationResult(true, "ようこそ鈴木さん");
    }
}

鈴木縛りw

XAML

<Window x:Class="ValidationSample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:ValidationSample="clr-namespace:ValidationSample"
    Title="Window1" Height="150" Width="300">
    <StackPanel>
        <Label Content="指名"/>
        <TextBox>
            <TextBox.Text>
                <Binding Path="Name" UpdateSourceTrigger="PropertyChanged">
                    <!--作成したルールを追加-->
                    <Binding.ValidationRules>
                        <ValidationSample:SuzukiValidationRule/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
    </StackPanel>
</Window>

実行結果

正しい値を入力したとき

f:id:griefworker:20081027102552p:image
見た目に変化無し。

不正な値を入力したとき

f:id:griefworker:20081027102625p:image
TextBox の枠が赤くなっています。

今日はこれだけ。