【发布时间】:2015-02-13 13:40:15
【问题描述】:
编辑
我的事情可能有点复杂,所以让我们保持简单。如果您将整数绑定到文本框,如果您在文本框中键入非法字符,它将获得验证异常。如何根据属性是否存在验证异常来禁用按钮。
原始问题#
我正在使用 MVVM 方法在 WPF 中创建一个应用程序,但没有任何框架。
我的模型类实现了 IDataErrorInfo,如果发生错误,它们都有一个 HasError 属性和一个
这很好用,但只适用于像
这样的显式数据注释 [MaxLength(3,ErrorMessage = "The text can't be longer than 3")]
[CustomRequiredAttribute]
public string CountryCode
{
get { return m_CountryCode; }
set { SetProperty(ref m_CountryCode, value); }
}
public string m_CountryCode;
另一方面,如果我将 Integer 绑定到文本框并输入非法字符(如字母),则 OnValidate 函数不会触发,因此错误不会添加到我的集合中。
如何捕获所有验证错误并将其添加到我的集合中?
string IDataErrorInfo.this[string propertyName]
{
get
{
var error = OnValidate(propertyName);
return error;
}
}
这是我的 CanExecute
protected override bool CanHandleSaveCommand()
{
return !Feeds.Any(e => e.HasErrors) && IsEdited;
}
为了让您得到完整的图片,OnValidate 方法可以正常工作
protected virtual string OnValidate(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentException("Invalid property name", propertyName);
}
var error_summary = new StringBuilder();
PropertyInfo property_info = GetType().GetProperty(propertyName);
var value = property_info.GetValue(this);
var validation_errors = new List<ValidationResult>();
var is_valid = Validator.TryValidateProperty(
value,
new ValidationContext(this, null, null)
{
MemberName = propertyName
},
validation_errors);
if (is_valid)
{
if (Errors.ContainsKey(propertyName))
{
Errors.Remove(propertyName);
PropertyChanged(this, new PropertyChangedEventArgs("HasErrors"));
HasErrorsChanged(this, EventArgs.Empty);
}
}
else
{
validation_errors.ForEach(e => error_summary.Append(e.ErrorMessage));
if (Errors.ContainsKey(propertyName))
Errors[propertyName] = error_summary.ToString();
else
Errors.Add(propertyName, error_summary.ToString());
PropertyChanged(this, new PropertyChangedEventArgs("HasErrors"));
HasErrorsChanged(this, EventArgs.Empty);
}
return error_summary.ToString();
}
【问题讨论】:
-
请检查我的编辑
标签: c# wpf validation mvvm