接上回的《WPF学习笔记(数据绑定篇2)》,继续
BindValidation
此示例演示了:
- 如何使用错误模板;
- 使用样式显示错误信息;
- 如何在校验发生异常时执行回调;

首先,你可以看见XAML中使用自定义的错误模板,指定错误模板的方式是:
<TextBox Name="textBox1" Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textBoxInError}" >
<TextBox.Text>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<Image Source="Error.jpg" Width="16" Height="16"/>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>(我在实验时,图像如果没有加入Width和Height,在显示时图片将变得很大)。
当然,你也可以使用样式绑定到异常上来显示错误,例如:
<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
BindingExpression myBindingExpression = textBox3.GetBindingExpression(TextBox.TextProperty);
Binding myBinding = myBindingExpression.ParentBinding;
myBinding.UpdateSourceExceptionFilter = new UpdateSourceExceptionFilterCallback(ReturnExceptionHandler);
myBindingExpression.UpdateSource();当然,为什么是ParentBinding呢?需要想想看。