1.驗證TextBox內容不超過指定長度,失去焦點后驗證。
前台:
<TextBox Name="tb1" Text="{Binding Name,Mode=TwoWay,ValidatesOnExceptions=True}" Height="100" Width="100"/>
后台:
Person p = new Person();
{
InitializeComponent();
p.Name = " 123 ";
tb1.DataContext = p;
}
public class Person : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set
{
if (value.Length > 3)
{
throw new Exception( " 不能超過三個字! ");
}
name = value;
NotifyChange( " Name ");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyChange( string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged( this, new PropertyChangedEventArgs(propertyName));
}
}
}
2.驗證TextBox內容不超過指定長度,不失去焦點驗證。只需要在上例的基礎上為TextBox添加TextChanged事件,並且在事件里通知數據源即可。
private void tb1_TextChanged(object sender, TextChangedEventArgs e)
System.Windows.Data.BindingExpression expresson = (sender as TextBox).GetBindingExpression(TextBox.TextProperty);
expresson.UpdateSource();
}
對驗證提示,可以進行樣式的設置。
前台添加NotifyOnValidationError屬性和BindingValidationError事件
<TextBox Name="tb1" Text="{Binding Name,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}" Height="100" Width="100" TextChanged="tb1_TextChanged" BindingValidationError="tb1_BindingValidationError"/>
后台實現BindingValidationError事件
private void tb1_BindingValidationError( object sender, ValidationErrorEventArgs e){
if (e.Action == ValidationErrorEventAction.Added)
{
(sender as TextBox).Background = new SolidColorBrush(Colors.Red);
}
else if (e.Action == ValidationErrorEventAction.Removed)
{
(sender as TextBox).Background = new SolidColorBrush(Colors.White);
}
}
3.標注的方式驗證。要添加System.ComponentModel.DataAnnotations.dll引用,並且將數據源的類定義修成為如下形式:
public class Person : INotifyPropertyChanged{
private string name;
[StringLength( 3, ErrorMessage = " 不能超過3個字,這是標注的方式驗證! " )]
public string Name
{
get { return name; }
set
{
Validator.ValidateProperty(value, new ValidationContext( this, null, null) { MemberName = " Name " });
name = value;
NotifyChange( " Name ");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyChange( string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged( this, new PropertyChangedEventArgs(propertyName));
}
}
}