1

我将 Prism+MVVM+C#+WPF 用于 LoB 应用程序。我创建了一个 ViewModelBase 类,它被我所有的 viewModel 继承。这个基类实现:

  • IViewModel(我的基本接口之一)
  • IDataErrorInfo(为了允许 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}"

您能否就如何防止初始验证提出建议?

提前致谢, 詹卢卡

4

0 回答 0