更新:2007 年 11 月
命名空间:
System.Windows.Controls 程序集:
PresentationFramework(在 PresentationFramework.dll 中)
用于 XAML 的 XMLNS:http://schemas.microsoft.com/winfx/xaml/presentation
Public NotInheritable Class DataErrorValidationRule _
Inherits ValidationRule
Dim instance As DataErrorValidationRule
public sealed class DataErrorValidationRule : ValidationRule
public ref class DataErrorValidationRule sealed : public ValidationRule
public final class DataErrorValidationRule extends ValidationRule
public final class DataErrorValidationRule extends ValidationRule
<DataErrorValidationRule .../>
使用 WPF 数据绑定模型可以将 ValidationRules 与 Binding 对象相关联。如果源对象实现 IDataErrorInfo 接口,则可以使用内置的规则 DataErrorValidationRule 来检查由 IDataErrorInfo 实现引发的错误。
用于显式设置 DataErrorValidationRule 的另一种语法是将 Binding 或 MultiBinding 对象上的 ValidatesOnDataErrors 属性设置为 true。
通过创建一个从 ValidationRule 派生的类,可以创建自定义规则。有关数据验证的更多信息和详细讨论,请参见数据绑定概述。
DataErrorValidationRule 是在 .NET Framework 3.5 版中引入的。有关更多信息,请参见.NET Framework 3.5 体系结构。
本示例演示如何针对自定义对象实现验证逻辑,然后绑定到该对象。
如果源对象实现了 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。
有关完整示例,请参见业务层验证示例。
System..::.Object
System.Windows.Controls..::.ValidationRule
System.Windows.Controls..::.DataErrorValidationRule
此类型的任何公共 static(在 Visual Basic 中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。
.NET Framework 和 .NET Compact Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。
.NET Framework
受以下版本支持:3.5 SP1、3.0 SP1
参考
其他资源