我正在为一个LoB应用程序使用Prism + MVVM + C#+ WPF。 我创建了一个ViewModelBase类,它由我的所有viewModel继承。 该基类实现:
它遵循我的IDataErrorInfo实现:
#region IDataErrorInfo members
public string this[string propertyName]
{
get { return this.Validate(propertyName); }
}
public string Error { get; private set; }
#endregion
protected string Validate(string propertyName)
{
this.Error = null;
PropertyInfo property = this.GetType().GetProperty(propertyName);
if (property == null)
throw new ArgumentException("propertyName");
foreach (ValidationAttribute attribute in property.GetCustomAttributes(typeof(ValidationAttribute), true))
{
try
{
object currentValue = property.GetValue(this, null);
attribute.Validate(currentValue, propertyName);
}
catch (ValidationException ex)
{
string errorMessage = (!string.IsNullOrWhiteSpace(attribute.ErrorMessage) ? attribute.ErrorMessage: ex.Message);
if (this.Error == null)
this.Error = errorMessage;
else
this.Error += string.Format("\r\n{0}", errorMessage);
}
}
return this.Error;
}
在应用程序的给定点,我正在以这种方式构建和关联View和ViewModel:
IViewModel viewModel = this.ServiceLocator.GetInstance(typeof(IMyViewModel)) as IMyViewModel;
IView view = this.ServiceLocator.GetInstance(type) as IMyView;
view.ViewModel = viewModel;
this.GlobalRegionManager.Regions[RegionNames.InnerRegion].Add(view);
当视图开始读取viewModel属性时会发生此问题。调用“this [string propertyName]”并执行验证功能......
在视图中,需要验证的属性的绑定定义为:
Text="{Binding SourceFileName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
您能否就如何防止初步验证提出建议?
提前致谢, 詹卢卡