我正在尝试验证用户输入,如上图所示。我正在使用 Fody Validor 库并按照此处的说明进行操作。
我可以看到验证正在进行,但 TextBox 边框没有变成红色。
我已经用 Google 搜索了,但我无法获得这方面的信息。任何人都可以为我提供一个工作代码示例吗?
更新
Fody ValidationTemplate(数据注解验证)
public class ValidationTemplate :IDataErrorInfo
{
INotifyPropertyChanged target;
ValidationContext validationContext;
List<ValidationResult> validationResults;
public ValidationTemplate(INotifyPropertyChanged target)
{
this.target = target;
validationContext = new ValidationContext(target, null, null);
validationResults = new List<ValidationResult>();
Validator.TryValidateObject(target, validationContext, validationResults, true);
target.PropertyChanged += Validate;
}
void Validate(object sender, PropertyChangedEventArgs e)
{
validationResults.Clear();
Validator.TryValidateObject(target, validationContext, validationResults, true);
var hashSet = new HashSet<string>(validationResults.SelectMany(x => x.MemberNames));
foreach (var error in hashSet)
{
OnValidate(error);
}
}
private HashSet<string> _errors = new HashSet<string>();
public string this[string columnName]
{
get
{
return OnValidate(columnName);
}
}
protected virtual string OnValidate(string propertyName)
{
string error = string.Empty;
try
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentException("Invalid property name", propertyName);
var value = this.GetType().GetProperty(propertyName).GetValue(this, null);
var results = new List<ValidationResult>(1);
var context = new ValidationContext(this, null, null) { MemberName = propertyName };
var result = Validator.TryValidateProperty(value, context, results);
if (!result)
{
var validationResult = results.First();
error = validationResult.ErrorMessage;
_errors.Add(propertyName);
}
else
{
_errors.Remove(propertyName);
}
}
catch (Exception) { }
return error;
}
public bool HasErrors
{
get { return _errors.Count > 0; }
}
public string Error { get; set; }
}
要验证的模型类:
public class Movie : INotifyPropertyChanged
{
IDataErrorInfo validationTemplate;
public Movie()
{
validationTemplate = new ValidationTemplate(this);
}
private int _id;
private string _title;
public int Id
{
get { return _id; }
set
{
if (_id != value)
{
_id = value;
OnPropertyChanged("Id");
}
}
}
[Required]
[StringLength(30)]
[MinLength(3)]
public string Title
{
get { return _title; }
set
{
if (_title != value)
{
_title = value;
OnPropertyChanged("Title");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
XAML
<TextBox Text="{Binding Movie.Title, Mode=TwoWay, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True, NotifyOnValidationError=True, ValidatesOnNotifyDataErrors=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />