- 创建 binding 对象,并设置属性
- BindingOperations.SetBinding 将 binding 对象与控件对象创建关联
代码绑定
// 创建绑定对象
var binding = new Binding
{
// 绑定源
Source = this.NameTextBox,
// 绑定相对源, 用于绑定到同一级的另一个控件的属性.
// binding.RelativeSource = new RelativeSource();
// 绑定路径
Path = new PropertyPath("Text"),
// 绑定更新触发器,控件失去焦点或是值变化时触发
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
// 数据绑定的方向
Mode = BindingMode.TwoWay,
// 绑定转换器, 对值进行转换
Converter = new StrLenValueConverter()
};
// 添加验证规则, 对输入的数据进行验证是否正确
binding.ValidationRules.Add(new DemoValidationRule());
// 添加一条内置规则,处理绑定异常,等效于 binding.ValidatesOnExceptions = true;,
binding.ValidationRules.Add(new ExceptionValidationRule());
// 如果希望发生错误时发生一个通知事件,则设置下面的属性, 事件类型 Validation.ErrorEvent
// 并在设置一个控件捕获事件进行处理上
binding.NotifyOnValidationError = true;
OutputTextBlock.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(Validation_Error));
// 将控件及对应的属性与 binding 进行绑定
BindingOperations.SetBinding(this.OutputTextBlock, TextBlock.TextProperty, binding);
// 绑定的简写格式
this.OutputTextBlock.SetBinding(TextBlock.TextProperty, binding);
ValidationRule
设置校验规则
// 1. 实现 ValidationRule 添加入 binding.ValidationRules
// 2. 当数据绑定发生异常时进入验证流程,下面两个等效
binding.ValidatesOnExceptions = true;
binding.ValidationRules.Add(new ExceptionValidationRule());
IDataErrorInfo
对象实现 IDataErrorInfo 接口进行校验
// 1. 绑定对象实现 IDataErrorInfo 接口
// 2. 进行如下设置,下面两条同效
binding.ValidatesOnDataErrors = true;
binding.ValidationRules.Add(new DataErrorValidationRule());
INotifyDataErrorInfo
与 IDataErrorInfo 类似, 感觉 INotifyDataErrorInfo 接口要简单一些
// 1. 绑定对象实现 INotifyDataErrorInfo 接口
// 2. 进行如下设置
binding.ValidatesOnNotifyDataErrors = true;
DataAnnotations
.net 有一套验证规则 DataAnnotations , 但是 wpf 不直接支持, 可以基于 IDataErrorInfo 或是 INotifyDataErrorInfo 接口然后调用 DataAnnotations 进行校验,编程宝典或是我的学习笔记中有相关代码,或是让 AI 实现
Validation.ErrorEvent 通知事件
检测到绑定错误时发送事件
// 如果希望发生错误时发生一个通知事件,则设置下面的属性, 事件类型 Validation.ErrorEvent
// 并在设置一个控件捕获事件进行处理上
binding.NotifyOnValidationError = true;
OutputTextBlock.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(Validation_Error));
界面显示
校验结果会给控件生成三个附加属性
- Validation.ErrorTemplate 有错误时显示的内容模板
- Validation.HasError 是否有校验错误
- Validation.Errors 校验的错误列表
下面定义一个错误提示样式, 在原控件外显示一个红框,并设置 ToolTip
<Window.Resources>
<!-- 一个简单的发生绑定错误时的设置模板 -->
<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}" x:Key="ErrorTextBoxStyle">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel>
<Border BorderBrush="Fuchsia" BorderThickness="3">
<!-- 表示原控件内容 -->
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<!-- 应用样式 -->
<TextBox x:Name="NameTextBox" Margin="5 10" Style="{StaticResource ErrorTextBoxStyle}" />