我过去这样做的一种方法是在 Model 上公开一个 ValidationDelegate,它允许 ViewModel 将自己的验证代码附加到模型。
通常我这样做是因为我将Model
层用作普通数据对象,所以我的模型只验证基本的东西,例如最大长度或非空值,而任何不特定于数据模型的高级验证都在 ViewModel 中完成。这通常包括诸如确保项目是唯一的,或者用户有权将值设置为特定范围的事情,甚至像您的情况一样,验证仅针对特定操作存在。
public class CustomerViewModel
{
// Keeping these generic to reduce code here, but it
// should include PropertyChange notification
public AddressModel Address { get; set; }
public CustomerViewModel()
{
Address = new AddressModel();
Address.AddValidationDelegate(ValidateAddress);
}
// Validation Delegate to validate Adderess
private string ValidateAddress(object sender, string propertyName)
{
// Do your ViewModel-specific validation here.
// sender is your AddressModel and propertyName
// is the property on the address getting validated
// For example:
if (propertyName == "Street1" && string.IsNullOrEmpty(Address.Street1))
return "Street1 cannot be empty";
return null;
}
}
这是我通常用于验证委托的代码:
#region IDataErrorInfo & Validation Members
#region Validation Delegate
public delegate string ValidationDelegate(
object sender, string propertyName);
private List<ValidationDelegate> _validationDelegates =
new List<ValidationDelegate>();
public void AddValidationDelegate(ValidationDelegate func)
{
_validationDelegates.Add(func);
}
public void RemoveValidationDelegate(ValidationDelegate func)
{
if (_validationDelegates.Contains(func))
_validationDelegates.Remove(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)
{
string s = null;
foreach (var func in _validationDelegates)
{
s = func(this, propertyName);
if (s != null)
return s;
}
return s;
}
#endregion // IDataErrorInfo for binding errors
#endregion // IDataErrorInfo & Validation Members