谢谢你们的帮助!以下是我决定解决问题的方法:
我创建了两个基类,一个用于普通模型(没有任何验证的模型。它只实现 INotifyPropertyChanged),另一个用于具有验证的模型,如下所示。
public abstract class ModelBase : INotifyPropertyChanged
{
//Implement INotifyPropertyChanged here
}
public delegate string ValidateProperty(string propertyName);
public abstract class ValidationModelBase : ModelBase, IDataErrorInfo
{
private bool _canValidate;
public bool CanValidate
{
get { return _canValidate; }
set { _canValidate = value; }
}
#region IDataErrorInfo Members
public string Error
{
get { return string.Empty; }
}
public string this[string columnName]
{
get
{
if (this.CanValidate)
{
return this.Validate(columnName);
}
return string.Empty;
}
}
#endregion
#region Validation Section
public event ValidateProperty OnValidateProperty;
public string Validate(string propertyName)
{
if (this.OnValidateProperty != null)
{
return OnValidateProperty(propertyName);
}
return string.Empty;
}
#endregion
}
现在我的模型看起来像这样:
public class ModelA : validationModelBase
{
public string PropertyA1 {get; set;}
public string PropertyA2 {get; set;}
}
public class ModelB : ValidationModelBase
{
public string Property B1 {get; set;}
public string Property B2 {get; set;}
}
那里没有很大的变化。ViewModel 现在看起来像这样:
public class ViewModel
{
public ModelA modelA {get; set;}
public ModelB modelB {get; set;}
public ViewModel()
{
this.modelA.OnValidateProperty += new ValidateProperty(ValidateModelA);
this.modelB.OnValidateProperty += new ValidateProperty(ValidateModelB);
}
private string ValidateModelA(string propertyName)
{
//Implement validation logic for ModelA here
}
private string ValidateModelB(string propertyName)
{
//Implement validation logic for ModelB here
}
}
到目前为止,这似乎对我有用。这样,任何具有验证的新模型只需要从 ValidationModelBase 派生并让 ViewModel 为验证事件添加事件处理程序。
如果有人有更好的方法来解决我的问题,请告诉我——我愿意接受建议和改进。