WPF-Bingding的数据校验

在进行数据校验时,我们需要用到ValidationRule类,ValidationRule类是一个抽象类,在使用的时候我们需要创建它的派生类并实现它的Validate方法,Validate方法的返回值是ValidationResult类型对象,如果校验通过就把ValidationResult对象的IsValid属性设置为true,反之设为false并为ErrorContent属性设置一个消息内容。
下面以一个程序为例:

UI

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="250" Width="359">
    <StackPanel Margin="0,0,0,0">
        <TextBox Name="textBox1" Text="textBox1"></TextBox>
        <Slider x:Name="slider1" Minimum="0" Maximum="100"></Slider>
    </StackPanel>
</Window>

用于校验的ValidationRule派生类

 public class RangeValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            double d = 0;
            if(double.TryParse(value.ToString(),out d))
            {
                if (d >= 0 && d <= 100)
                {
                    return new ValidationResult(true, null);
                }
            }
            return new ValidationResult(false, "Validation Failde");
        }
    }

建立Binding

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Binding binding = new Binding("Value") { Source = this.slider1 };
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;//设置目标控件值发生变化时,源数据立马更新
            RangeValidationRule rvr = new RangeValidationRule();
            binding.ValidationRules.Add(rvr);
            textBox1.SetBinding(TextBox.TextProperty, binding);
        }  
    }

下面我们看下校验的结果
正常情况

在这里插入图片描述
输入不符合校验的值情况
在这里插入图片描述

Binding进行校验时的默认行为是认为来自Source的数据是正确的,只有来自Target的数据才有错误(可以等价于用户输入的数据)。我们如果需要开启校验
rvr.ValidatesOnTargetUpdated = true;//开启Target校验
举例来说,如以上的程序如果Solider的Value出现非正常值的时候,如-1,这样如果不开启Target校验,会出现问题。

我们观察这个校验会发现一个问题,我门在校验错误的时候,返回的错误信息去哪了?

 return new ValidationResult(false, "Validation Failde");

在这段代码里的Validation Failde这条信息。这里如果需要显示这条信息需要用到路由事件,首先在创建Binding时要把Binding对象的NotifyOnValidationError属性设置为true,这样在数据校验失败的时候就会发出一个信号。
完整的Binding代码如下

 public MainWindow()
        {
            InitializeComponent();
            Binding binding = new Binding("Value") { Source = this.slider1 };
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;//设置目标控件值发生变化时,源数据立马更新
            RangeValidationRule rvr = new RangeValidationRule();
            rvr.ValidatesOnTargetUpdated = true;//开启Target校验
            binding.ValidationRules.Add(rvr);

            binding.NotifyOnValidationError = true;
            textBox1.SetBinding(TextBox.TextProperty, binding);
            this.textBox1.AddHandler(Validation.ErrorEvent,new RoutedEventHandler(ValidationError));
        }  

侦听检验错误事件的事件处理器

 void ValidationError(object sender,RoutedEventArgs e)
        {
            if (Validation.GetErrors(this.textBox1).Count > 0)
            {
                this.textBox1.ToolTip = Validation.GetErrors(this.textBox1)[0].ErrorContent.ToString();
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Maybe_ch

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值