数据验证方法补充ValidationRule

引言

除了使用CommunityToolkit.Mvvm工具包的ObservableValidator,.Net 抽象类VlidationRule也可以让我们实现自定义验证方法,但验证很受限,只能对当前值进行判断,无法获取对象的上下文。

ValidationRule

功能:验证值是否在0~100之间。

cs 复制代码
public class MyValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        double myValue = 0;
        if (double.TryParse(value.ToString(), out myValue))
        {
            if (myValue >= 0 && myValue <= 100)
                {
                    return new ValidationResult(true, null);
                }
        }
        return new ValidationResult(false, "Input should between 0 and 100");
    }
}

使用如下:

ValidationRules下面可以添加多个验证条件。

XML 复制代码
<TextBox Height="50" Margin="5,30,5,240" Name="tbx1" Validation.Error="tbx1_Error">
    <TextBox.Text>
          <Binding ElementName="slider" Path="Value" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
                <Binding.ValidationRules>
                      <hc:RegexRule Type = "Number"/>
                      <local:RangeValidationRule ValidatesOnTargetUpdated="True"/>
                </Binding.ValidationRules>
           </Binding>
    </TextBox.Text>
</TextBox>
相关推荐
Lost of 程序猿4 小时前
M2 实战:询价与采购订单聚合落地——跨聚合一致性、领域事件与 Outbox
开发语言·c#·asp.net·.net
有梦想的咕噜6 小时前
Newtonsoft.Json (Json.NET) 常用方法汇总
linux·json·.net
jiushidt2 天前
ArcGIS Pro Add‑in 打包流程详解
arcgis·c#·.net·arcgispro
半亩码田2 天前
【.NET新特性·第17篇】EF Core 10 与 Aspire 13.1
python·flask·.net
小羊没烦恼!2 天前
Office文件的奥秘——.NET平台下不借助Office实现Word、Powerpoint等文件的解析(完)
java·大数据·前端·网络·word·powerpoint·.net
张人玉3 天前
基于 C# / .NET 8 + Windows Forms + SQLite 的桌面银行业务演示系统——华夏示范银行管理系统
windows·sqlite·c#·.net
慧都小妮子3 天前
.NET 报表控件选型对比:Stimulsoft 与 FastReport 怎么选
c#·.net·报表开发·数据可视化·报表控件·报表引擎选型
我是唐青枫3 天前
C#.NET PInvoke 深入解析:封送、内存布局与原生互操作实战
开发语言·c#·.net
geovindu3 天前
CSharp: Strategy Pattern
开发语言·后端·c#·.net·.netcore·策略模式·行为模式
geovindu3 天前
CSharp: Task Scheduler
开发语言·后端·c#·.net·.netcore