WPF 中的验证 - 自定义验证规则或 IDataErrorInfo
作为一名新的 WPF 程序员,我无法找到验证用户输入的两种不同方式之间的区别:
针对实现 IDataErrorInfo 编写自定义验证规则的优点和缺点是什么,反之亦然?我什么时候应该选择其中一种而不是另一种?
更新:
虽然我已经得到了答案,但我发现相关文章可能对其他人有帮助。
As a new WPF programer I cant find the difference between two different way to validate user input:
What are the pros and cons of writing custom validation rule against implementing IDataErrorInfo, and vice versa? WhenShould I prefer one over the other?
Update:
Though I got my answer already, I found related article that may help others.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本上,如果您实现 IDataErrorInfo,验证将在绑定对象中实现,而如果您实现验证规则,验证将在附加到绑定的对象中实现。
就我个人而言,如果您使用 MVVM,我认为您必须疯狂才能使用除
IDataErrorInfo
之外的任何内容。您希望验证存在于视图模型中。如果它在您的视图模型中,那么它是集中的并且是可测试的。如果它在您的视图中,那么您的验证逻辑可能是错误的或丢失的,找到它的唯一方法是手动测试您的视图。这是可避免的错误的巨大潜在来源。有些地方使用验证规则是有意义的 - 例如,如果您正在围绕哑对象(例如
XmlDataSource
)构建 UI。但对于大多数生产应用程序,我不会接近它。Basically, if you implement
IDataErrorInfo
, validation is implemented in the bound object, whereas if you implement validation rules, validation is implemented in objects attached to the binding.Personally, if you're using MVVM, I think you'd have to be crazy to ever use anything except
IDataErrorInfo
. You want validation to live in the view model. If it's in your view model, it's centralized and it's testable. If it's in your view, then your validation logic can be wrong, or missing, and the only way to find it is by manually testing your view. That's a huge potential source of avoidable bugs.There are places where it makes sense to use validation rules - if, for instance, you're building a UI around dumb objects (an
XmlDataSource
, for example). But for most production applications, I wouldn't go near it.IDataErrorInfo
验证规则
验证类在整个应用程序中重用它。
我的观点是,对于常见的验证,如必填字段验证、电子邮件地址验证,您可以使用验证规则。如果您需要进行自定义验证,例如范围验证或任何自定义验证,请使用 IDataerrorinfo。
IDataErrorInfo
Validation Rule
validations class reuse it throughout the application.
My opinion is, for common validation like required field validations, email address validattions you can use validation rule. If you need to do custom validations like range validations , or whatever custom validation use IDataerrorinfo.
您实现 IDataErrorInfo 以便能够将数据绑定与 eas 一起使用。您仍然可以构建自定义验证规则。
You implement IDataErrorInfo to be able to use databinding with eas. You still build your custom validation rules.