更改IDataErrorInfo被调用时

时间:2013-04-24 13:40:25

标签: wpf validation xaml idataerrorinfo

我尝试将验证配置为仅在单击“保存”按钮时触发。我从来没有使用过IDataErrorInfo,所以从一开始我就不知道如何设置它。我试图保持MVVM路径。有什么我可以调用手动让点击保存按钮验证我的字段?

实施:

 IDataErrorInfo

Textbox 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

    }

1 个答案:

答案 0 :(得分:1)

我使用IValidateableObject。如果对象类实现了此接口,则它会公开您可以覆盖的validate方法,然后您可以仅在需要时在object.validate上调用此验证。它返回true或false。在该验证函数中,您可以循环遍历对象属性,并根据您的自定义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

}