2011-07-28 35 views
6

是否有可能使用System.ComponentModel.DataAnnotations及其屬於屬性(如Required,Range,...)在WPF或Winforms類?如何使用WPF或Winforms應用程序中的System.ComponentModel.DataAnnotations

我想把我的驗證屬性。

感謝

編輯1:

我寫這篇文章:

public class Recipe 
{ 
    [Required] 
    [CustomValidation(typeof(AWValidation), "ValidateId", ErrorMessage = "nima")] 
    public int Name { get; set; } 
} 

private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     var recipe = new Recipe(); 
     recipe.Name = 3; 
     var context = new ValidationContext(recipe, serviceProvider: null, items: null); 
     var results = new List<System.ComponentModel.DataAnnotations.ValidationResult>(); 

     var isValid = Validator.TryValidateObject(recipe, context, results); 

     if (!isValid) 
     { 
      foreach (var validationResult in results) 
      { 
       MessageBox.Show(validationResult.ErrorMessage); 
      } 
     } 
    } 

public class AWValidation 
{ 
    public bool ValidateId(int ProductID) 
    { 
     bool isValid; 

     if (ProductID > 2) 
     { 
      isValid = false; 
     } 
     else 
     { 
      isValid = true; 
     } 

     return isValid; 
    }   
} 

但即使我設置3到我的財產什麼happend

+0

重複的問題在:http://stackoverflow.com/questions/1755340/validate-data-using-dataannotations-with-wpf-entity-framework – Raghu

回答

8

是,you can。這裏的another article說明了這一點。你可以通過手動創建一個ValidationContext做到這一點,即使在一個控制檯應用程序:

public class DataAnnotationsValidator 
{ 
    public bool TryValidate(object @object, out ICollection<ValidationResult> results) 
    { 
     var context = new ValidationContext(@object, serviceProvider: null, items: null); 
     results = new List<ValidationResult>(); 
     return Validator.TryValidateObject(
      @object, context, results, 
      validateAllProperties: true 
     ); 
    } 
} 

UPDATE:

下面是一個例子:

public class Recipe 
{ 
    [Required] 
    [CustomValidation(typeof(AWValidation), "ValidateId", ErrorMessage = "nima")] 
    public int Name { get; set; } 
} 

public class AWValidation 
{ 
    public static ValidationResult ValidateId(int ProductID) 
    { 
     if (ProductID > 2) 
     { 
      return new ValidationResult("wrong"); 
     } 
     else 
     { 
      return ValidationResult.Success; 
     } 
    } 
} 

class Program 
{ 
    static void Main() 
    { 
     var recipe = new Recipe(); 
     recipe.Name = 3; 
     var context = new ValidationContext(recipe, serviceProvider: null, items: null); 
     var results = new List<ValidationResult>(); 

     var isValid = Validator.TryValidateObject(recipe, context, results, true); 

     if (!isValid) 
     { 
      foreach (var validationResult in results) 
      { 
       Console.WriteLine(validationResult.ErrorMessage); 
      } 
     } 
    } 
} 

注意,ValidateId方法必須是public靜態並返回ValidationResult而不是布爾值。還要注意傳遞給TryValidateObject方法的第四個參數,如果您要對自定義驗證器進行評估,則必須將其設置爲true。

+0

尼斯,文章參考+1。 –

+0

謝謝,但我不正確undestand你的代碼。你的代碼工作?爲什麼?我想爲什麼時候例如Filed1有價值2恩錯誤消息返回 – Arian

+0

請參閱我的編輯1 – Arian

相關問題