Silverlight數據驗證實現技巧分享
Silverlight開發工具對于編程人員來說是一個非常有用的多媒體處理平臺。其中有很多功能與應用技巧值得我們去深入的研究。在這里我們就為大家介紹一下有關Silverlight數據驗證的實現方法。#t#
首先我們編寫一個簡單的業務類,由于數據綁定驗證只能在雙向綁定中,所以這里需要實現INotifyPropertyChanged接口,如下Silverlight數據驗證代碼所示,在set設置器中我們對于數據的合法性進行檢查,如果不合法則拋出一個異常:
- /// < summary>
- /// Author:TerryLee
- /// http://www.cnblogs.com/Terrylee
- /// < /summary>
- public class Person :
INotifyPropertyChanged - {
- public event PropertyChanged
EventHandler PropertyChanged; - private int _age;
- public int Age
- {
- get { return _age; }
- set {
- if (value < 0)
- throw new Exception("年齡輸入不合法!");
- _age = value;
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new
PropertyChangedEventArgs("Age")); - }
- }
- }
- private String _name = "Terry";
- public String Name
- {
- get { return _name; }
- set {
- if (value.Length < 4)
- throw new Exception("姓名輸入不合法!");
- _name = value;
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new
PropertyChangedEventArgs("Name")); - }
- }
- }
- public void NotifyPropertyChanged
(String propertyName) - {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new Property
ChangedEventArgs(propertyName)); - }
- }
- }
編寫Silverlight數據驗證,如下代碼所示,設置NotifyOnValidationError和ValidatesOnExceptions屬性為true,并且定義BindingValidationError事件:
- < !--
- http://www.cnblogs.com/Terrylee
- -->
- < StackPanel Orientation=
"Horizontal" Margin="10">- < TextBox x:Name="txtName"
Width="200" Height="30"- Text="{Binding Name,Mode=TwoWay,
- NotifyOnValidationError=true,
- ValidatesOnExceptions=true}"
- BindingValidationError="txtName_
BindingValidationError">- < /TextBox>
- < my:Message x:Name="messageName">
< /my:Message>- < /StackPanel>
- < StackPanel Orientation=
"Horizontal" Margin="10">- < TextBox x:Name="txtAge"
Width="200" Height="30"- Text="{Binding Age,Mode=TwoWay,
- NotifyOnValidationError=true,
- ValidatesOnExceptions=true}"
- BindingValidationError="txtAge_
BindingValidationError">- < /TextBox>
- < my:Message x:Name=
"messageAge">< /my:Message>- < /StackPanel>
實現BindingValidationError事件,在這里可以根據ValidationErrorEventAction來判斷如何進行處理,在界面給出相關的提示信息等,如下Silverlight數據驗證代碼所示:
- /// < summary>
- /// Author:TerryLee
- /// http://www.cnblogs.com/Terrylee
- /// < /summary>
- void txtAge_BindingValidationError
(object sender, ValidationErrorEventArgs e)- {
- if (e.Action == ValidationError
EventAction.Added)- {
- messageAge.Text = e.Error.
Exception.Message;- messageAge.Validation = false;
- }
- else if (e.Action == Validation
ErrorEventAction.Removed)- {
- messageAge.Text = "年齡驗證成功";
- messageAge.Validation = true;
- }
- }
通過這樣的方式,我們就可以實現Silverlight數據驗證。