嗨,您将不得不在我的代码中创建一些验证注释的方法,例如 ValidateMethod
public class ViewModel:INotifyPropertyChanged,IDataErrorInfo
{
int _password;
[Required(ErrorMessage = "Field 'Range' is required.")]
[Range(1, 10, ErrorMessage = "Field 'Range' is out of range.")]
public int Password
{
get
{
return _password;
}
set
{
if (_password != value)
{
_password = value;
Validate("Password", value);
Notify("Password");
}
}
}
private void Validate(string propertyName, object value)
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentNullException("propertyName");
string error = string.Empty;
var results = new List<System.ComponentModel.DataAnnotations.ValidationResult>(2);
bool result = Validator.TryValidateProperty(
value,
new ValidationContext(this, null, null)
{
MemberName = propertyName
},
results);
if (!result && (value == null || ((value is int || value is long) && (int)value == 0) || (value is decimal && (decimal)value == 0)))
return;
if (!result)
{
System.ComponentModel.DataAnnotations.ValidationResult validationResult = results.First();
if (!errorMessages.ContainsKey(propertyName))
errorMessages.Add(propertyName, validationResult.ErrorMessage);
}
else if (errorMessages.ContainsKey(propertyName))
errorMessages.Remove(propertyName);
}
#region INotifyPropertyChanged
public void Notify(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region IDataErrorInfo
public string Error
{
get { throw new NotImplementedException(); }
}
private Dictionary<string, string> errorMessages = new Dictionary<string, string>();
public string this[string columnName]
{
get
{
if(errorMessages.ContainsKey(columnName))
return errorMessages[columnName];
return null;
}
}
#endregion
}
>xml
<TextBox Text="{Binding Password, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" Height="70" Width="200" />
xml.cs
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
您需要从应用 DataAnnotations 的属性的 setter 调用 Validate 方法,并确保在通知 PropertyChanged 之前调用它。