1

我正在尝试将我的验证配置为仅在单击保存按钮时触发。我以前从未使用过 IDataErrorInfo,所以从一开始我就不太清楚如何设置它。我试图保持 MVVM 路径。有什么我可以调用来手动验证我的字段单击保存按钮吗?

实施:

 IDataErrorInfo

文本框 XAML:

     Text="{Binding Name, Mode=TwoWay, ValidatesOnDataErrors=True}" />         

代码:

    public string Error
    {
        get { throw new NotImplementedException(); }
    }

    public string this[string columnName]
    {
        get
        {
            if (columnName == "Name")
            {
                if (!Name.Length() >= 6)
                {
                    return "Name must be 6 chars.";
                }
                else
                {
                    return null;
                }
            }
            return null;
        }
    } 

保存命令:

    private void Save() {
       //db save, etc..
       Need to validate all properity fields

    }
4

1 回答 1

1

我使用 IValidateableObject。如果您的对象类实现了此接口,它公开了您可以覆盖的 validate 方法,那么您可以仅在需要时在 object.validate 上调用此验证。它返回真或假。在该验证函数中,您可以遍历对象属性并根据您的自定义 bunisness 逻辑将所需的列添加到 IDataerrorInfo。我通过创建一个由我的模型/对象类继承的 Validationbase 类来做到这一点。

这是我的验证基类的示例,您可以将其继承到模型/对象类中:

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class ValidationBase : IValidatableObject, IDataErrorInfo, INotifyPropertyChanged
{

         #region "DECLARATIONS"
         protected Dictionary<string, string> _propertyErrors = new Dictionary<string, string>();
         protected List<ValidationResult> _validationResults = new List<ValidationResult>();
         public bool HasErrors {
                 get { return (_propertyErrors.Count + _validationResults.Count) > 0; }
         }
         #endregion
         #region "IValidatableObject IMPLEMENTATION"
         public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
         {
                 return null;
         }
         #endregion
         #region "iDataError OBJECTS"
         //Returns an error message
         //In this case it is a general message, which is
         //returned if the list contains elements of errors
         public string Error {
                 get {
                          if (_propertyErrors.Count > 0) {
                                   return "Object data is invalid";
                          } else {
                                   return null;
                          }
                 }
         }

         public string this[string columnName] {
                 get {
                          if (_propertyErrors.ContainsKey(columnName)) {
                                   return _propertyErrors[columnName].ToString();
                          } else {
                                   return null;
                          }
                 }
         }

         #endregion
         #region "IDataError FUNCTIONS"
         //Adds an error to the collection, if not already present
         //with the same key
         protected void AddError(string columnName, string msg)
         {
                 if (!_propertyErrors.ContainsKey(columnName)) {
                          _propertyErrors.Add(columnName, msg);
                          OnPropertyChanged(columnName);
                 }
         }

         //Removes an error from the collection, if present
         protected void RemoveError(string columnName)
         {
                 if (_propertyErrors.ContainsKey(columnName)) {
                          _propertyErrors.Remove(columnName);
                          OnPropertyChanged(columnName);
                 }
         }
         public void ClearErrors()
         {
                 _propertyErrors.Clear();
         }
         #endregion
         #region "INotifyPropertyChanged IMPLEMENTATION"
         public event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged;
         public delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);

         protected virtual void OnPropertyChanged(string propertyName)
         {
                 if (PropertyChanged != null) {
                          PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                 }
         }
         #endregion

}

如果您使用实体框架作为模型,我相信将在通过 db.SaveChanges 保存对象之前调用 validate 方法

以下是如何在模型中实现验证库:

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public partial class vendor : ValidationBase
{

    #region "PROPERTIES"
    public bool HasChanges { get; set; }
    #endregion

    #region "VALIDATION FUNCTIONS"

    public override IEnumerable<ComponentModel.DataAnnotations.ValidationResult> Validate(ComponentModel.DataAnnotations.ValidationContext validationContext)
    {
        return base.Validate(validationContext);
        PropertyValitaion(true);
    }

    public void PropertyValitaion(bool bAllProperties, string sProperty = "")
    {
        //your property specific logic goes here


    }
    #endregion

}
于 2013-04-24T20:49:30.753 回答