关于Silverlight Input Data Validation <一>
2011-02-17 17:50 步丈天涯 阅读(574) 评论(4) 收藏 举报先说说基于INotifyPropertyChanged接口的数据验证。
要点:
1.NotifyOnValidationError和ValidatesOnExceptions在默认情况下是False的,所以,要想让验证失败的消息显示出来,请把它设置为True。
2.请指定你所要验证地控件的DataContext。
3.如果你想等验证通过时再做其他的事,用Validation.GetHasError()。
以下是我的代码:
(1)xaml部分:
//对应上面的要点1
<TextBox Text="{Binding Mode=TwoWay, Path=MyID, NotifyOnValidationError=True, ValidatesOnExceptions=True}" MaxLength="6" Name="txtMyID" Height="25" Width="100" />
(2)xaml.cs部分:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
//对应上面的要点2
MyPageValidation mv = new MyPageValidation();
txtMyID.DataContext = mv;
}
private void btnClick_Click(object sender, RoutedEventArgs e)
{
//对应上面的要点3
if(!Validation.GetHasError(this.txtMyID))
{
}
}
}
(3)MyPageValidation验证类部分:
public class MyPageValidation : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _MyID;
int resultId;
public string MyID
{
get
{
return _MyID;
}
set
{
if (value.Length == 0)
{
throw new InvalidDataException("Please enter ID!");
}
if (!Int32.TryParse(value, out resultId))
{
throw new InvalidDataException("Please enter Integer!");
}
_MyID = value;
//如果我注释掉下面这段代码,验证照样正常执行
//所以,我还没弄清楚这段代码的作用
//知道的请告诉我,谢谢
NotifyPropertyChanged("MyID");
}
}
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
(4)我的自定义Exception部分:
public class InvalidDataException : Exception
{
public InvalidDataException(string msg) : base(msg)
{
}
}
浙公网安备 33010602011771号