Data annotation and wpf validation

两盒软妹~` 提交于 2019-12-12 05:24:58

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7820588/data-annotation-and-wpf-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!