.net - 类级验证

标签 .net wpf data-annotations validation

我正在验证一个类 DataAnnotations 实用程序。

我有一个类有 Title属性(property)和Item属性(property)。
我要申请 RequiredAttribute Title属性,但只有在 Item 时才应该是无效的属性为空;如果Item属性是用一个对象设置的,Title不需要。

简而言之,我想要 RequiredAttribute 仅在满足类中的条件时才进行验证。

如何才能做到这一点。

更新

由于我没有找到其他方法,而且由于我通常不经常需要此功能,因此我决定使用类级验证器使其成为粗略的方法。
我的问题是,有没有办法手动更新 UI 以使标题文本框带有红框,即使其无效?

更新 2
我希望类级验证器在一个字段上进行总结。
例如,我必须字段 Cost 和 SalesPrice,我想确保 SalesPrice > Cost 并且使 SalesPrice 无效,否则我不希望在类级别出现全局验证错误。

我更喜欢以 xamly 的方式来做。

最佳答案

您可以通过为类创建自定义验证属性来做到这一点。不幸的是,据我所知,分配给属性的 DataAnnotation 属性无法访问父类的其他属性,因此需要创建一个类验证器。
使用 System.ComponentModel.DataAnnotations 命名空间,您需要创建从 ValidationAttribute 继承的自定义属性类并覆盖 IsValid 方法(我没有测试下面的代码,但它应该可以帮助您):

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
sealed public class CustomAttribute: ValidationAttribute
{
  public CustomAttribute()
  {
  }

  public override bool IsValid(object value)
  {
     if(value is myClass)
     {
       return ((myClass)value).Item != null &&
         string.IsNullOrEmpty(((myClass)value).Title) ? false : true;
     }
     else return true;
  }
}

再深入一点,似乎虽然跨领域验证不可能开箱即用,但可以通过扩展框架来支持它来实现。见 this article for details ,希望这将被添加到 MVC 的 future 版本中。

关于.net - 类级验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3880727/

相关文章:

c# - 带触摸屏的 WPF,列表框打开模式窗口没有响应

asp.net-mvc - Html.TextBoxFor 仅接受大于零的数字

c# - 不同系统配置的最佳IO线程数

c# - 自定义 "No http resource was found that matches the request uri"消息

c# - 在 Windows 7 下为非管理员用户提供目录的完全控制

c# - 如何调用验证属性进行测试?

c# - DataAnnotations 属性是否已缓存?如果是这样,如何在不同文化之间切换?

c++ - 添加新行后未获取数据表行

c# - 如何在使用 XAML 获取图像资源后释放/缓存图像资源

c# - WPF Datagrid IValueConverter ConvertBack 自己类的对象