Silverlight Validator
<dataInput:Label Margin="4" Target="{Binding ElementName=firstName}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" Content="First Name" />
<TextBox x:Name="firstName" Text="{Binding FirstName, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" Grid.Row="0" Grid.Column="1" Margin="4" />
<TextBlock Text="Explicit Label content" Grid.Row="0" Grid.Column="3" VerticalAlignment="Center" Margin="4" />
/// <summary>
/// 数据提交时判断数据是否满足规则
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Submit_Click(object sender, RoutedEventArgs e)
{
var validationContext = new ValidationContext(contactGrid.DataContext, null, null);
List<ValidationResult> validationResults = new List<ValidationResult>();
if (!Validator.TryValidateObject(contactGrid.DataContext, validationContext, validationResults,true))
{
HtmlPage.Window.Alert("Validation failed");
}
else
{
HtmlPage.Window.Alert("Validation passed");
}
}
public class Person : INotifyPropertyChanged
{
/// <summary>
/// Represents the first name of the contact.
/// </summary>
private string firstName;
/// <summary>
/// Gets or sets the first name of the contact.
/// </summary>
[Required]
[Display(Name = "First Name", GroupName = "Name")]
//[StringLength(10, ErrorMessage = "the length of First Name is between 5 and 10", MinimumLength = 2)]//这种写法在最开始绑定值时,出现异议,如果能保证最开始加载的数据正常,可以加上此判断
public string FirstName
{
get
{
return firstName;
}
set
{
//判读value != firstName 有好处,也有坏处,好处是,值没有变化的时候,不触发OnPropertyChanged 事件,坏处是,如果一开始绑定的数据就是null,本事就不对,可是不会触发
if (value != firstName)
{
//不能使用这种方式,使用这种方式,异常肯定只能出现一次,下次出现不了
//Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "FirstName" });
//firstName = value;
//OnPropertyChanged("FirstName");
firstName = value;
OnPropertyChanged("FirstName");
Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "FirstName" });
}
}
}
/// <summary>
/// Raises a property changed notification for the specified property name.
/// </summary>
/// <param name="propName">The name of the property that changed.</param>
protected virtual void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
#region INotifyPropertyChanged Members
/// <summary>
/// Raised when a property on the contact changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
浙公网安备 33010602011771号