对于基于业务规则的验证,我通常公开一个验证委托,我的ViewModel可以设置。
例如,包含您的收藏视图模型可能是这样的:
public ParentViewModel()
{
foreach(var user in UserCollection)
user.AddValidationErrorDelegate(ValidateUser);
}
private string ValidateUser(object sender, string propertyName)
{
if (propertyName == "Email")
{
var user = (UserVM)sender;
if (UserCollection.Count(p => p.Email== user.Email) > 1)
return "Another user already has this Email Address";
}
return null;
}
的想法是,你Model
应该只包含原始数据,因此它应该只验证原始数据。这可以包括验证最大长度,必填字段和允许的字符等内容。包含业务规则的业务逻辑应在ViewModel
中进行验证,并允许这样做。
在UserVM
类实际执行的我IDataErrorInfo
应该是这样的:
#region IDataErrorInfo & Validation Members
/// <summary>
/// List of Property Names that should be validated
/// </summary>
protected List<string> ValidatedProperties = new List<string>();
#region Validation Delegate
public delegate string ValidationErrorDelegate(object sender, string propertyName);
private List<ValidationErrorDelegate> _validationDelegates = new List<ValidationErrorDelegate>();
public void AddValidationErrorDelegate(ValidationErrorDelegate func)
{
_validationDelegates.Add(func);
}
#endregion // Validation Delegate
#region IDataErrorInfo for binding errors
string IDataErrorInfo.Error { get { return null; } }
string IDataErrorInfo.this[string propertyName]
{
get { return this.GetValidationError(propertyName); }
}
public string GetValidationError(string propertyName)
{
// If user specified properties to validate, check to see if this one exists in the list
if (ValidatedProperties.IndexOf(propertyName) < 0)
{
//Debug.Fail("Unexpected property being validated on " + this.GetType().ToString() + ": " + propertyName);
return null;
}
string s = null;
// If user specified a Validation method to use, Validate property
if (_validationDelegates.Count > 0)
{
foreach (ValidationErrorDelegate func in _validationDelegates)
{
s = func(this, propertyName);
if (s != null)
{
return s;
}
}
}
return s;
}
#endregion // IDataErrorInfo for binding errors
#region IsValid Property
public bool IsValid
{
get
{
return (GetValidationError() == null);
}
}
public string GetValidationError()
{
string error = null;
if (ValidatedProperties != null)
{
foreach (string s in ValidatedProperties)
{
error = GetValidationError(s);
if (error != null)
{
return error;
}
}
}
return error;
}
#endregion // IsValid Property
#endregion // IDataErrorInfo & Validation Members
我喜欢@Rachel了这里的方法。我一直在使用IDataErrorInfo.this []从模型中暴露范围错误,但只有在用户单击确定后才能运行业务规则检查。在用户完成填写表单的其余部分并单击确定之前,能够使用像这样的方法将业务规则错误暴露给UI *是很好的。 – Kendrick
这就是我正在寻找的!填写表单时,通过IDataErrorInfo执行“更高级别”检查的一种非常好且简单的方法。 :) – Christian