WPF textbox 绑定 slider 的值 进行数据验证

 

 

 

<Window x:Class="WpfDemo.BindingValidationDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="BindingValidationDemo" Height="300" Width="300">
    <Grid>
        <StackPanel x:Name="stackPanel1">
            <TextBox Height="49" x:Name="textBox1"></TextBox>
            <Slider Height="48" Minimum="-10" Maximum="110" x:Name="silder"></Slider>
        </StackPanel>
    </Grid>
</Window>

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfDemo
{
    /// <summary>
    /// BindingValidationDemo.xaml 的交互逻辑
    /// </summary>
    public partial class BindingValidationDemo : Window
    {
        public BindingValidationDemo()
        {
            InitializeComponent();

            //source
            Binding bind = new Binding("Value") { Source = this.silder };

            //如果不啟用,則不會觸發 Validation.ErrorEvent 路由事件
            bind.NotifyOnValidationError = true;//获取 校验失败的信息

            //当 target 变化时,更新 source,就是輸入的值會同步更新到source 控件裡面
            bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

            RangeValidationRule rvr = new RangeValidationRule();
            //target的值綁定了Source的值,Validate只針對Target,
            //不針對Source,所以要設定ValidatesOnTargetUpdated ,來對Target進行檢測
            //當target更新時觸發這個有效檢測
            rvr.ValidatesOnTargetUpdated = true;

            bind.ValidationRules.Add(rvr);
            //target
            this.textBox1.SetBinding(TextBox.TextProperty,bind);

            //添加validationError事件
            //this.textBox1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(ValidationError));
            this.stackPanel1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(ValidationError));

        }
        public void ValidationError(object sender,RoutedEventArgs args)
        {
            //if (Validation.GetErrors(this.textBox1).Count > 0)
            //{
            //    this.textBox1.ToolTip = Validation.GetErrors(this.textBox1)[0].ErrorContent.ToString();
            //}
            //else
            //{
            //    this.textBox1.ToolTip = null;
            //}
            TextBox tb = args.OriginalSource as TextBox;
            if(tb != null&&tb.Name== "textBox1")
            {
                if (Validation.GetErrors(tb).Count > 0)
                {
                    tb.ToolTip = Validation.GetErrors(tb)[0].ErrorContent.ToString();
                }
                else
                {
                    tb.ToolTip = null;
                }
            }
        }
    }
    class RangeValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            double x = 0;
            if (double.TryParse(value.ToString(), out x))
            {
                if (x >= 0 && x <= 100)
                {
                    return new ValidationResult(true, null);
                }
                else
                {
                    return new ValidationResult(false, "输入数值超出范围");
                }
            }
            return new ValidationResult(false, "输入数值异常");

        }
    }
}

  

posted @ 2021-07-29 20:32  zq爱生活爱代码  阅读(66)  评论(0编辑  收藏  举报