WPF学习笔记(数据绑定篇3)

接上回的《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 >
注意这个模板是ControlTemplate(为什么是控件模板我也不知道,照葫芦画瓢),然后定义了一个布局,左边一个图像,右边一个AdornedElementPlaceholder占位符。
(我在实验时,图像如果没有加入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呢?需要想想看。

转载于:https://www.cnblogs.com/tansm/archive/2007/09/30/902996.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值