2012-12-06 18 views
0

您好我正在搜索這個問題,但我沒有找到任何有關這個。DataAnnotations:if(valid)=>更改屬性

我要傑尼設定的財產,如果每DataAnnotations驗證失敗

你能告訴我什麼,我在我的代碼錯過?

型號Codesnip

 private string _firstname; 
     public string Firstname 
     { 
      get { return _firstname; } 
      set 
      { 
       _firstname = value; 
       RaisePropertyChanged(() => Reg(() => Firstname)); 
      } 
     } 

視圖模型Codesnip

 [Required] 
     [RegularExpression(@"^[a-zA-ZäöüßÄÖÜß''-'\s]{2,40}$")] 
     public string Name 
     { 
      get { return currentperson.Name; } 
      set 
      { 
       currentperson.Name = value; 
      RaisePropertyChanged(() => Reg(() => Name)); 
      } 
     } 

查看Codesnip

<TextBox HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Text="{Binding Firstname,UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/> 

任何幫助,將不勝感激

編輯:添加校驗類

public class VMValidation : VMBase, IDataErrorInfo 
{ 
    private Dictionary<string, string> ErrorList = new Dictionary<string, string>(); 

    /// <summary> 
    /// Gets a value indicating whether or not this domain object is valid. 
    /// </summary> 
    public bool IsVailid 
    { 
     get { return (ErrorList.Count == 0) ? true : false; } 
    } 

    #region IDataErrorInfo 

    /// <summary> 
    /// Gets an error message indicating what is wrong with this domain object. 
    /// The default is an empty string (""). 
    /// </summary> 
    public string Error 
    { 
     get { return getErrors(); } // noch keine richtige methode für gefunden müsste so aber auch funktionieren 
    } 

    /// <summary> 
    /// dies ist eine methode die durch einen Event (noch unbekannt welcher) 
    /// ausgelöst wird und den Propertynamen schon mit übergeben bekommt 
    /// </summary> 
    /// <param name="propertyName">Name der Property z.B FirstName</param> 
    /// <returns>The error message for the property. 
    /// The default is an empty string ("").</returns> 
    public string this[string propertyName] 
    { 
     get { return OnValidate(propertyName); } 
    } 

    private string getErrors() 
    { 
     string Error = ""; 
     foreach (KeyValuePair<string, string> error in ErrorList) 
     { 
      Error += error.Value; 
      Error += Environment.NewLine; 
     } 

     return Error; 
    } 

    /// <summary> 
    /// Validates current instance properties using Data Annotations. 
    /// </summary> 
    /// <param name="propertyName">Name der Property</param> 
    /// <returns>ErrorMsg</returns> 
    protected virtual string OnValidate(string propertyName) 
    { 
     if (string.IsNullOrEmpty(propertyName)) 
      throw new ArgumentException("Invalid property name", propertyName); 

     string error = string.Empty; 
     var value = this.GetType().GetProperty(propertyName).GetValue(this, null); 
     var results = new List<ValidationResult>(1); 

     var context = new ValidationContext(this, null, null) { MemberName = propertyName }; 

     var result = Validator.TryValidateProperty(value, context, results); 

     if (!result) 
     { 
      var validationResult = results.First(); 
      error = validationResult.ErrorMessage; 
     } 
     if (error.Length > 0) 
     { 
      if (!ErrorList.ContainsKey(propertyName)) 
       ErrorList.Add(propertyName, error); 
     } 
     else 
      if (!ErrorList.ContainsKey(propertyName)) 
       ErrorList.Remove(propertyName); 

     return error; 
    } 

    public bool VailidValue(string propertyName, object value) 
    { 
     var results = new List<ValidationResult>(1); 
     var context = new ValidationContext(this, null, null) { MemberName = propertyName }; 
     var result = Validator.TryValidateProperty(value, context, results); 

     return result; 
    } 
    #endregion //IDataErrorInfo 
} 

回答

1

嘗試創建驗證方法,和僅設置值,如果結果是true

public string Name 
{ 
    get { return currentperson.Name; } 
    set 
    { 
     if (ValidateProperty("Name", value)) 
     { 
      currentperson.Name = value; 
      RaisePropertyChanged(() => Reg(() => Name)); 
     } 
    } 
} 

protected bool ValidateProperty(string propertyName, object value) 
{ 
    var results = new List<ValidationResult>(); 
    bool isValid = Validator.TryValidateProperty(
     value, 
     new ValidationContext(this, null) 
     { 
      MemberName = propertyName 
     }, 
     results); 
    // Do what you want with the validation results 
    return isValid; 
} 
+0

mmhh現在我IDataErrorInfo的驗證失敗,因爲該物業始終是有效的... –

+0

因此,要麼讓財產(這會觸發驗證)並在保存實體之前對其進行驗證,或者可以將ValdiationResult錯誤添加到IDataErrorInfo.Error屬性中。如果合適,我會使用INotifyDataErrorInfo,因此可能觸發多個錯誤。 – Alyce

+0

INotifyDataErrorInfo在.NET WPF 4.0上的VisualStudio中不可用AFAIK –

1

我改變了我的VMValidation

 public class VMValidation : VMBase, IDataErrorInfo 
     { 
      private Dictionary<string, string> ErrorList = new Dictionary<string, string>(); 

      public bool IsVailid 
      { 
       get { return (ErrorList.Count == 0) ? true : false; } 
      } 

      #region IDataErrorInfo 

      public string Error 
      { 
       get { return getErrors(); } // noch keine richtige methode für gefunden müsste so aber auch funktionieren 
      } 

      public string this[string propertyName] 
      { 
       get { return OnValidate(propertyName); } 
      } 

      private string getErrors() 
      { 
       string Error = ""; 
       foreach (KeyValuePair<string, string> error in ErrorList) 
       { 
        Error += error.Value; 
        Error += Environment.NewLine; 
       } 

       return Error; 
      } 

      protected virtual string OnValidate(string propertyName) 
      { 
       string error =String.Empty; 

       if (ErrorList.ContainsKey(propertyName)) 
        error = ErrorList[propertyName]; 

       return error; 
      } 

      public bool VailidateValue(string propertyName, object value) 
      { 
       if (string.IsNullOrEmpty(propertyName)) 
       { 
        Logger.ERRROR(propertyName, "Invalid property name"); 
        throw new ArgumentException("Invalid property name", propertyName); 
       } 

       var results = new List<ValidationResult>(1); 
       var context = new ValidationContext(this, null, null) { MemberName = propertyName }; 
       var result = Validator.TryValidateProperty(value, context, results); 

       if (!result) 
       { 
        var validationResult = results.First(); 
        string error = validationResult.ErrorMessage; 

        if (error.Length > 0) 
        { 
         if (!ErrorList.ContainsKey(propertyName)) 
          ErrorList.Add(propertyName, error); 
        } 
       } 
       else 
        if (ErrorList.ContainsKey(propertyName)) 
         ErrorList.Remove(propertyName); 

       return result; 
      } 
      #endregion //IDataErrorInfo 
     } 

,做Alyce建議

 [Required] 
     [RegularExpression(@"^[a-zA-ZäöüßÄÖÜß''-'\s]{2,40}$")] 
     public string Name 
     { 
      get 
      { 
       if (currentperson == null) 
        return ""; 
       return currentperson.Name; 
      } 
      set 
      { 
       if (VailidateValue("Name", value)) 
       { 
        currentperson.Name = value; 
       } 
       RaisePropertyChanged(() => Reg(() => Name)); //you have to Raise because otherwise you won't get the Error :) 
      } 
     }