首页 > 其他分享 >【WPF】二、Validation 数据验证

【WPF】二、Validation 数据验证

时间:2022-10-31 01:00:24浏览次数:76  
标签:StudentName return string 验证 value Length WPF Validation public

上一篇:【WPF】一、WPF 数据验证机制 Validation---重要

只设计Mvvm的View层和Viewmodel层,未设计到model。下面一篇重点介绍IDataErrorInfo|INOtyfyDataErrorInfo +数据标注的联合使用,主要在model层

  1. By using Exception validation
  2. By using IDataErrorInfo
  3. By using ValidationRules

By Using Exception Validation

The View
<TextBox Text="{Binding StudentName, 
                ValidatesOnExceptions=True,
                UpdateSourceTrigger=PropertyChanged}" 
                VerticalAlignment="Center" 
                FontSize="20"/>
The Code behind View
namespace TestWpfValidation
{
    public partial class MainWindow : Window
    {
        private string _studentName;

        public string StudentName
        {
            get { return _studentName; }
            set
            {
                if (value.Length < 6 || value.Length > 50)
                {
                    throw new ArgumentException("Name should be between range 6-50");
                }

                _studentName = value;
            }
        }

        public MainWindow()
        {
            this.DataContext = this;
            InitializeComponent();
        }
    }
}

Output

Image 2

By Using IDataErrorInfo

The View
TextBox Text="{Binding StudentName, 
               UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" 
               VerticalAlignment="Center" 
               FontSize="20"/>
The ViewModel
public partial class MainWindow : Window, IDataErrorInfo, INotifyPropertyChanged
    {
        public MainWindow()
        {
            this.DataContext = this;
            InitializeComponent();
        }

        public string StudentName
        {
            get { return _studentName; }
            set
            {
                _studentName = value;
                OnPropertyChanged("StudentName");
            }
        }

        public string this[string columnName]
        {
            get
            {
                string result = String.Empty;
                if (columnName == "StudentName")
                {
                    if (StudentName.Length < 6 || StudentName.Length > 10)
                    {
                        result = "Name should be between range 3-50";
                    }
                }

                return result;
            }
        }

        public string Error
        {
            get
            {
                return string.Empty;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        private string _studentName;
}

By Using ValidationRules

public class StudentNameValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            string valueToValidate = value as string;
            if (valueToValidate.Length < 6 || valueToValidate.Length > 10)
            {
                return new ValidationResult(false, "Name should be between range 3-50");
            }

            return new ValidationResult(true, null);
        }
}

In XAML,

<TextBox VerticalAlignment="Center" FontSize="20"> 
      <TextBox.Text> 
       <Binding Path="StudentName" UpdateSourceTrigger="PropertyChanged"> 
            <Binding.ValidationRules> 
                 <local:StudentNameValidationRule/> 
            </Binding.ValidationRules> 
       </Binding> 
      </TextBox.Text> 
<TextBox>

Adding Style to the Error

<Style x:Key="GeneralErrorStyle">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel>
                            <TextBlock DockPanel.Dock="Right"
                                       Foreground="Red"
                                       FontSize="12pt"
                                       Text="Error"
                                       ToolTip="{Binding ElementName=placeholder, 
                                       Path= AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
                            <AdornedElementPlaceholder x:Name="placeholder" />
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

XaML

<TextBox Style="{StaticResource GeneralErrorStyle}"
                 Text="{Binding StudentName, 
                        UpdateSourceTrigger=PropertyChanged, 
                        ValidatesOnDataErrors=True}"
                 HorizontalAlignment="Left"
                 Width="300"/>

 

标签:StudentName,return,string,验证,value,Length,WPF,Validation,public
From: https://www.cnblogs.com/cdaniu/p/16842897.html

相关文章

  • javax.validation 请求参数校验小问题: @Min 不校验是否为空
    想用@Min来校验是否为空, 结果发现不行, 看来是必须用到@NotNull 注解了.如下. 我的代码是:@Min(value=0,message=MsgCdConstant.AMOUNT_MUST_BE_POSITIVE)h......
  • js滑动验证
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content......
  • wpf利用ReoGrid控件进行Excel表格展示及导出
    Nuget包安装Nuget包管理器直接搜索ReoGrid进行安装,如图   前端根据官方文档(https://reogrid.net/document/installation/)在前端引入命名空间:xmlns:rg="clr-na......
  • Python接入微信公众号Token验证
    注意点官方示例是Pthon2版本的,如果是Python3版本需要有改动验证成功返回echostr要是数字格式的公众号侧配置(公众号后台-基本配置)服务器侧配置代码部分......
  • 数据验证
    日常项目开发中,对于前端提交的表单I后台接口接收到表单数据后,为了程序的严谨性,通常后端会加入业务参数的合法校验操作来避免程序的非技术性bug,这里对于客户端提交的数据......
  • WPF里ItemsControl的分组实现
    一、WPF里ItemsControl的分组实现我们在用到ItemsControl时,有时会用到分组。如下图所示,绑定一个普通一个数组如下所示:数据类型为:publicclassStudent{......
  • 5.用户手机验证码登录
    用户手机验证码登录一、yapi接口文档二、代码实现1.服务提供者1.1在tanhua-dubbo-db模块创建Mapper接口com/tanhua/dubbo/mappers/UserMapper.java(数据层,查询数据库)p......
  • 3.登录发送验证码
    登录发送验证码1.接口说明2.流程分析客户端发送请求服务端调用第三方组件发送验证码验证码发送成功,存入redis响应客户端,客户端跳转到输入验证码页面3.代码实现3......
  • C# 开发微信小程序 系列(1) 接入服务器 验证token
    目前官方小程序验证只有PHP的,暂未发现C#版本的 ,本人研究后贴出来大家分享下。有不懂的请留言,本人会尽快回复的:  废话不多说直接上代码:   ///<summary>//......
  • 【已验证】使用composer 出现Could not find a matching version of package xxx
    今天使用composer安装一个包,开始我指定了版本,报错但是我后来,没有指定版本,还是报错??去百度查了下,出现这个问题,有两个原因:你设置的composer的原有问题(我的源我都用了好......