Data annotations and wpf validation

Is there a way that I use data annotation as a validation source in WPF? I want to define a class like:

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

      

And then bind it to a field in the view and wpf confirm that the user is entering some value for that field and also make sure its length is less than 50. I know I can write a validator for that, but then if I change maxLength to say 60, then I need to change it in the validator and I don't want to have changes in different places.

0


source to share


2 answers


You need to create a metadata class definition. You will need something like this:

[MetadataTypeAttribute(typeof(LocationGroup.LocationGroupMetadata))]
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 metadata to support validation.

0


source


Since this question is still unanswered and I stumbled upon it while answering another question that was looking for the same thing, I would share a solution to this question here too.



Microsoft TechNet Article "Data Validation in MVVM " is a very simple and thorough implementation of using data annotations for validation in WPF. I've read this solution myself and have recommended it to others.

0


source







All Articles