方法 : カスタム オブジェクトに検証ロジックを実装する
更新 : 2007 年 11 月
次のコード例は、カスタム オブジェクトに検証ロジックを実装してバインドする方法を示しています。
使用例
次の例に示すように、ソース オブジェクトで IDataErrorInfo を実装する場合は、ビジネス層に検証ロジックを実装できます。
public class Person : IDataErrorInfo
{
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public string Error
{
get
{
return null;
}
}
public string this[string name]
{
get
{
string result = null;
if (name == "Age")
{
if (this.age < 0 || this.age > 150)
{
result = "Age must not be less than 0 or greater than 150.";
}
}
return result;
}
}
}
次の例では、テキスト ボックスのテキスト プロパティが Person オブジェクトの Age プロパティにバインドされています。このプロパティは、x:Keydata が指定されたリソース宣言によってバインディング可能になっています。DataErrorValidationRule は、IDataErrorInfo の実装によって発生した検証エラーをチェックします。
<TextBox Style="{StaticResource textBoxInError}">
<TextBox.Text>
<!--By setting ValidatesOnExceptions to True, it checks for exceptions
that are thrown during the update of the source property.
An alternative syntax is to add <ExceptionValidationRule/> within
the <Binding.ValidationRules> section.-->
<Binding Path="Age" Source="{StaticResource data}"
ValidatesOnExceptions="True"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<!--DataErrorValidationRule checks for validation
errors raised by the IDataErrorInfo object.-->
<!--Alternatively, you can set ValidationOnDataErrors="True" on the Binding.-->
<DataErrorValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
また、DataErrorValidationRule を使用する代わりに、ValidatesOnDataErrors プロパティを true に設定する方法もあります。
サンプル全体については、「ビジネス層の検証のサンプル」を参照してください。