数据注释和wpf验证
有什么方法可以使用数据注释作为 WPF 中的验证源吗?我希望能够定义一个类,例如:
class myData
{
[Required]
[MaxLength(50)]
public string Name{get;set;}
}
然后将其绑定到视图中的字段,并且 wpf 验证用户为此字段输入一些值,并确保其长度不大于 50。我知道我可以为此编写一个验证器,但是如果我将 maxLength 更改为 60,那么我需要在验证器中更改它,并且我不想在不同的地方进行更改。
Is there any way that I use data annotation as the source of validation in WPF? I want to be able to define a class such as:
class myData
{
[Required]
[MaxLength(50)]
public string Name{get;set;}
}
And then bind it to a field in a view and the wpf validate that user enter some value for this field and also make sure that its length is not greater than 50. I know that I can write a validator for this, but then if I change the maxLength to say 60, then I need to change it in validator and I don't want to have changes in different places.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要创建该类的“元数据”定义。您将需要这样的东西:
这使用必要的元数据来扩展类以支持验证。
You need to create a "metadata" definition of the class. You'll need something like this:
This extends the class with the necessary meta data to support the validation.
由于这个问题仍然没有得到解答,并且我在回答另一个正在寻找相同内容的问题时遇到了它,我会也在这里分享这个问题的解决方案。
Microsoft TechNet 文章“数据MVVM 中的验证”是在 WPF 中使用数据注释进行验证的非常干净且彻底的实现。我自己通读了该解决方案并将其推荐给其他人。
Since this question is still left unanswered and I came across it while answering another question that was looking for the same thing, I would share the solution of that question over here too.
The Microsoft TechNet article "Data Validation in MVVM" is a very clean and thorough implementation of using Data Annotations for validation in WPF. I read through the solution myself and would recommend it to others.