WPF第八章绑定数据验证

上传人:do****y1 文档编号:169596681 上传时间:2022-11-16 格式:DOCX 页数:10 大小:177.51KB
返回 下载 相关 举报
WPF第八章绑定数据验证_第1页
第1页 / 共10页
WPF第八章绑定数据验证_第2页
第2页 / 共10页
WPF第八章绑定数据验证_第3页
第3页 / 共10页
点击查看更多>>
资源描述
一、通过代码实现数据绑定通过代码实现数据绑定,使用的是System.Windows.Data命名空间的Binding类,主要使用Binding 类的如下的属性: Source属性:绑定到的数据源 Mode 属性:绑定的模式(0neTime、OneWay、TwoWay、OneWayToSource 或 Default) Path属性:绑定到的数据源的属性 Conve rte r属性:绑定时所使用的类型转换器在绑定目标控件上使用SetBinding方法添加数据绑定。例如将MyData的Name属性绑定到txtName 控件的Text属性上,使用MyColo rConve rter转换器将MyBindingColo r的ColoObject属性绑定到r ec控件的Fill属性上:1: MyData data = new MyData();2:3: Binding bindingl = new Binding();4: bindingl.Source = data;5: binding1.Mode = BindingMode.OneWay;6: binding1.Path = new PropertyPath(Name);7:8: txtName.SetBinding(TextBox.TextProperty, binding);9:10:11: MyBindingColor color = new MyBindingColor();12:13: Binding binding2 = new Binding();14: binding2.Source = color;15: binding2.Mode = BindingMode.OneWay;16: binding2.Path = new PropertyPath(ColorObject);17: binding2.Converter = new MyColorConverter();18:19: rec.SetBinding(Rectangle.FillProperty, binding2);二、实现绑定数据的验证:对于绑定数据的验证,系统采用如下的机制:345678910111213141516DataErrorValidationRule:检查由源对象的IDataErrorlnfo实现所引发的错误,要求数据源 对象实现 System.ComponentModel 命名空间的 IDataErrorInfo 接口。例如,定义一个学生信息类,要求其学生成绩在0到100间,学生姓名的长度在2到10个字符间:public class StudentInfoWithValidation : IDataErrorInfo#region构造方法public StudentInfoWithValidation()StudentName =Tom;Score = 90;public StudentInfoWithValidation(string m_StudentName,double m_Score)StudentName = m_StudentName;Score = m_Score;#endregion#region 属性public string StudentName1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061get; set;public double Scoreget; set;#endregion#region 实现 IDataErrorInfo 接口 的成员public string Errorgetreturn null;public string thisstring columnNamegetstring result = null;switch (columnName)case StudentName:/设置StudentName属性的验证规则int len = StudentName.Length;if (len 10)result StudentName length must between 2 and 10;break;case Score:/设置Score属性的验证规则if (Score 100)result Score must between 0 and 100 ;break;return result;62:63:64:#endregion65: 在界面上,定义两个TextBox绑定到StudentName和Score两个属性上,并设置其采用DataErrorV alidationRule:1: 6:7:8:9:10:11:12:13:StudentName:14:Score:15:、16:17:21:22:23:24:25:26:27:28:29:30:31:32:33:Get Student Info34:Get Validate State35:36: 1 nDataErrorVa 1 idati on Ru 1 e.CZI回Student Marne:Tomabcd 亡 fghiScore:900Get Student InfoGet Validate StateSystem InfbrnnationStudent Name isTomabcdefghiScore is 900.I W i nDataErrorVa I idati on Ru le.System InformationStu den t Name is Tom,Score is 90.从执行的结果上来看,当验证出现错误(即索引器属性返回的字符串不为空时),系统默认给出一种验证 错误的显示方式(控件以红色边框包围),但是需注意两点:如果系统出现异常,如成绩值输入“90d”则系统不会显示错误,控件上的输入值也不赋值到数据源。这种情况下,需要使用ExceptionValidationRule。ExceptionValidationRule :即当绑定目标的属性值向绑定源的属性值赋值时引发异常所产生的验证。此种方式若实现自定义的逻辑验证,通常设置数据源的属性的Set访问器,在Set访问器中,根据输入 的值结合逻辑,使用throw抛出相应的异常。例如上例中,对于Score对应的TextBox,再加入ExceptionValidationRule:1: 2:3:4:5:6:7:ExceptionValidationRule /8:9:10:11: f j vVanDataErrorvahdationRule.自定义验证规则:定义一个类,继承ValidationRule抽象类,实现其Validate方法,验证某一输入。例如,定义一个类,用来验证输入的Email地址是否合法(验证的Email允许为字符串的空值String.E mpty,但有输入必须符合Email的格式要求)在学生类中添加Email可读可写属性(并不做相应的验证,忽略其他重复代码):1: public string Email2: 3:set; get;4: 定义一个类,实现Email格式验证:1: using System.Globalization;2: using System.Text.RegularExpressions;3: using System.Windows.Controls;4567891011121314151617181920212223242526272829303132333435363738394041424344454647namespace WPFDataBindingDemo public class EmailValidationRule : ValidationRulepublic override ValidationResult Validate(object value, CultureInfo cultureInfo) bool isValid = false;string message = null;/检查输入值不为空,且是字符串if (value != null & value is string)string email = value.ToString();/检查输入的字符串是否为String.Emptyif (email != string.Empty)string emailFormartRegex =(w-.+)(0-91,3.0-91,3.0-91,3.)|” + ”(w-+.)+)(a-zA-Z2,4|0-91,3)(?)$”;/检查输入的字符串是否符合Email格式isValid = Regex.IsMatch(email, emailFormartRegex);if (! isValid)messageInput string not match Email Format ;else/输入的字符串为字符串空值时,认为验证通过isValid true;elsemessage Input value is NULL or is not string.;/返回验证结果(ValidationResult对象)return new ValidationResult(isValid,message);49: 在界面上:1: 2:Binding Mode=TwoWay Path=Email UpdateSourceTrigger=PropertyChanged3:4:5:6:St jdentName:Tommicro5oft.coincriScore:Get Student InfoGet Validate State7: 2:3:4:5:Trigger Property=Validation.HasError Value=True6:Setter Property=Background Value=#DDD /7:Setter Property=Foreground Value=Red /8:Setter Property=ToolTip9:Value=Binding RelativeSource=RelativeSource Self,Path=(Validation.Errors)0.ErrorContent/10:/Trigger三、为数据验证提供视觉效果在数据验证错误后,可以通过以下两种方式提供相应的视觉效果:定义Style及相应的触发器如果要使输入的控件的外观发生变化,可以使用Style。例如上例中出错,使输入的文本框的背景颜色和 字体颜色发生变化,并提供ToolTip显示错误信息,可以定义如下的Style:1: 11:/Style.Triggers12: 效果如下:1 W i n DataErro rVa 1 idati on Ru 1 eDemo回Score:Email:*Get Student Info Get Validate State定义控件模板如果要为相应的控件添加一些辅助的控件,可以使用控件模板,如出现验证错误时,不使用系统默认的红 色边框,而是在文本框后添加一个红色的星号:1: 2:3:4:*5:6: 并在每一个输入的TextBox中添加:1: Validation.ErrorTemplate=StaticResource validErrorTextBoxTemplateWin DatalE rrorV a lidation Ru le.=回St jdentName:Get Validate StateI 1 WinDataErrorValidationRuIe. L 1=1Email:Get Student Info
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 办公文档 > 解决方案


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!