WPF验证的实现方式比较灵活,对于初学者来说掌握起来并不是非常的轻松。我们在这里为大家详细介绍了具体的操作方法,希望对大家有所帮助。#t#
一.两步实现WPF验证
(1)实现INotifyPropertyChanged接口,并为验证的属性添加需要验证的元数据
- [StringLengthValidator(1, 10,
MessageTemplate = "First Name
must be between 1 and 15 characters")] - public string FirstName
- {
- get { return this.firstName; }
- set
- {
- this.firstName = value;
- this.OnPropertyChanged("FirstName");
- }
- }
(2)在前端使用Validizor控件,为后端验证显示错误
- < Validizor Source="
{Binding FirstName}"/>- < TextBox Text="{Binding
FirstName,UpdateSource
Trigger=PropertyChanged}"/>
WPF验证二.使用EnterpriseLibrary验证组
(1)指定元数据Ruleset属性
- [StringLengthValidator(1, 20,
MessageTemplate = "Last Name
must be between 1 and 20
characters", Ruleset = "Default")]- public string LastName
- {
- get { return this.lastName; }
- set
- {
- this.lastName = value;
- this.OnPropertyChanged("LastName");
- }
- }
(2)前端控件同时指定Ruleset属性
- < Validizor Source=
"{Binding LastName}"
Ruleset="Default">
三.内置WPF验证的缺陷
(1)ui错误无法变更,验证的不仅仅只是TextBox(3.5 sp1 可以把错误信息转嫁)
wpf内置验证的做法,自定义ValidationRule
(2)若使用了内置验证做法,控件的验证将会失效
四.两个属性以上的WPF验证
(1)单一的元数据标签无法做到,需要写额外的方法进行验证
(2)使用HasSelfValidation元数据标签验证对象
- [HasSelfValidation]
- public class Person2 :
INotifyPropertyChanged- {
- }
(3)添加验证方法
- [SelfValidation(Ruleset
= "Default")]- public void ValidateDefault
(ValidationResults results)- {
- }
(4)针对特定属性来验证
(4)-1 实行IPropertyChangedName接口,根据进来的属性进行判断,可以填写多个方法用于区分
- [SelfValidation(Ruleset =
"Default")]- public void ValidateDefault
(ValidationResults results)- {
- switch (this.PropertyChangedName)
- {
- case "FirstName":
- break;
- }
- }
- [SelfValidation(Ruleset =
"Default")]- public void ValidateDefault
(ValidationResults results)- {
- switch (this.PropertyChangedName)
- {
- case "LastName":
- break;
- }
- }
(5)前端控件指定