WPF-ValidationRule 数据验证

本文介绍了一个WPF应用程序中如何实现数据绑定和验证功能。通过一个简单的年龄输入框示例,展示了如何设置数据绑定规则及自定义验证逻辑,确保用户输入的数据符合预期的有效范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="192" Width="537"
    xmlns:local="clr-namespace:WpfApplication1">

    <Window.Resources>
        <!--判断规则-->
        <local:NumberRangeRule x:Key="numberRangeRule"></local:NumberRangeRule>
    </Window.Resources>

    <Grid Name="grid" ClipToBounds="False"  Height="129" Width="297">
        <Label HorizontalAlignment="Left" Margin="25,53,0,0" Name="label2" Width="49" Height="28" VerticalAlignment="Top">年龄:</Label>
        <!--绑定 Error Content 到ToolTip-->
        <TextBox Margin="94,50,0,56"   ToolTip="{Binding RelativeSource={RelativeSource self}, Path=(Validation.Errors)[0].ErrorContent}" 
                 Name="txtAge" HorizontalAlignment="Left" Width="101">
            <TextBox.Text>
                <!--绑定Age数据 和 判断规则 并设置最大最小值-->
                <Binding Path="Age" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:NumberRangeRule Min="0" Max="128" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
    </Grid>
</Window>

以上是前台Xaml,下面是后台C#代码:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Navigation;
using System.Windows.Shapes;

using System.ComponentModel;

namespace WpfApplication1
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        public Person person;
        public Window1()
        {
            InitializeComponent();

            //创建示例数据并绑定
            person = new Person();
            person.Name = "kill";
            person.Age = 21;
            this.txtAge.DataContext = person;
        }
    }

    //数据类要继承INotifyPropertyChanged
    public class Person : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }

        public Person() { }   
    }

    //书写继承ValidationRule的判断规则类
    //重写Validate方法完成自己的判断
    public class NumberRangeRule : ValidationRule
    {
        int min;
        public int Min
        {
            get { return min; }
            set { min = value; }
        }

        int max;
        public int Max
        {
            get { return max; }
            set { max = value; }
        }

        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            int number;
            if (!int.TryParse((string)value, out number))
            {
                return new ValidationResult(false, "Invalid number format");
            }

            if (number < min || number > max)
            {
                return new ValidationResult(false, string.Format("Number out of range ({0} - {1})", min, max));
            }

            return ValidationResult.ValidResult;
        }
    }

}

 

-----------------------------转自大佬小寒https://home.cnblogs.com/u/xh831213/——————————————————————————————

转载于:https://www.cnblogs.com/zuguofanrongfuqiang/p/7883175.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值