输入验证1

这篇博客介绍了一个WPF应用中如何利用RelativeSourceSelf进行TextBox内的数据验证。通过创建一个自定义的RangeRule验证类,实现了对TextBox输入值范围的限制,确保数值在0到20之间。当输入值超出范围时,会显示错误提示。
摘要由CSDN通过智能技术生成

可以做一个虚假的绑定,比如绑定到自身:

 
  1. <StackPanel>

  2. <TextBox>

  3. <TextBox.Text>

  4. <Binding RelativeSource="{RelativeSource Self}" Path="Tag" UpdateSourceTrigger="PropertyChanged">

  5. <Binding.ValidationRules>

  6. <local:RangeRule Min="0" Max="20" />

  7. </Binding.ValidationRules>

  8. </Binding>

  9. </TextBox.Text>

  10. </TextBox>

  11. </StackPanel>

 
  1. public class RangeRule : ValidationRule

  2. {

  3. public int Min { get; set; }

  4. public int Max { get; set; }

  5. public override ValidationResult Validate(object value, CultureInfo cultureInfo)

  6. {

  7. int num;

  8. if (!int.TryParse(value as string, out num) || num < Min || num > Max)

  9. return new ValidationResult(false, "Please enter a number in the range: " + Min + " - " + Max + ".");

  10. else

  11. return new ValidationResult(true, null);

  12. }

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值