バリデーション
最終更新:
atachi
TextBoxへのバリデーション適応

入力値が不正

入力値が正しい

バリデーションルールの作成
ValidationRuleクラスのサブクラスを作成し、Validateメソッドをオーバーライドします。
このメソッドが返すValidationResult型には、バリデーションが成功したか失敗したかのフラグを持ち、失敗時にはその理由を設定することができます。
下記のルールは入力値がカタカナで構成されているかどうかを判別するルールです。
namespace WpfTextBox
{
public class KatakanaRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value is string)
{
string o = value as string;
Regex regex = new Regex(@"^[ア-ヾ]+$");
if (!regex.IsMatch(o))
{
return new ValidationResult(false, "カタカナ以外の文字が含まれています。");
}
}
else
{
return new ValidationResult(false,"文字が設定されていません");
}
return new ValidationResult(true, null);
}
}
}
バリデーション失敗時のコントロールテンプレートを設定
WPFのTextBoxにはバリデーション失敗時の処理が含まれていません。
バリデーション失敗時に表示するレイアウトをコントロールテンプレートとしてリソースに定義します。
「icon_alert.gif」は検証失敗を促す「!」マークのアイコンです。フリーのものを借りました。
<ControlTemplate x:Key="TextBoxErrorTemplate">
<StackPanel>
<StackPanel Orientation="Horizontal">
<Image Height="16" Margin="0,0,5,0" Source="/WpfTextBox;component/Assets/icon_alert.gif"/>
<AdornedElementPlaceholder x:Name="Holder"/>
</StackPanel>
<Label Foreground="Red"
Content="{Binding ElementName=Holder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
</StackPanel>
</ControlTemplate>
TextBoxの設定
最後にTextBoxに作成したバリデーションルールの設定と、バリデーション失敗時に表示するコントロールテンプレートを設定します。
<TextBox Margin="10" Name="tbValidTest" VerticalAlignment="Top" Width="250"
Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}">
<TextBox.Text>
<Binding Path="Label" Source="{StaticResource myobject}" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<my:KatakanaRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
補足とか
「{StaticResource myobject}」は下記のようなクラスを静的リソースとして定義したものです。
Labelプロパティだけをメンバに持ちます。
namespace WpfTextBox
{
public class MyData
{
public MyData(){
Label = "";
}
public string Label { get; set; }
}
}