2011-07-28 38 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

相关问题