如何:在自定义对象上实现验证逻辑
更新: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。
有关完整示例,请参见业务层验证示例。