数据注释和wpf验证

发布于 2024-12-11 07:23:09 字数 286 浏览 1 评论 0原文

有什么方法可以使用数据注释作为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

看轻我的陪伴 2024-12-18 07:23:09

您需要创建该类的“元数据”定义。您将需要这样的东西:

[MetadataTypeAttribute(typeof(MyClass.MyClassMetadata))]
public partial class MyClass
{
    internal sealed class MyClassMetadata
    {
        // Metadata classes are not meant to be instantiated.
        private MyClassMetadata()
        {
        }

        [Required]
        [MaxLength(50)]
        public string Name{ get; set; }
    }
}

这使用必要的元数据来扩展类以支持验证。

You need to create a "metadata" definition of the class. You'll need something like this:

[MetadataTypeAttribute(typeof(MyClass.MyClassMetadata))]
public partial class MyClass
{
    internal sealed class MyClassMetadata
    {
        // Metadata classes are not meant to be instantiated.
        private MyClassMetadata()
        {
        }

        [Required]
        [MaxLength(50)]
        public string Name{ get; set; }
    }
}

This extends the class with the necessary meta data to support the validation.

内心荒芜 2024-12-18 07:23:09

由于这个问题仍然没有得到解答,并且我在回答另一个正在寻找相同内容的问题时遇到了它,我会也在这里分享这个问题的解决方案。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文