Do Data Annotations only work with ASP.NET?

160 views Asked by At

This is a serious question, because for the life of me after 2 days I still can't get Data Annotations to work with my classes in a WPF application. And it seems every Google article involving data annotations mentions ASP, MVC or some other web based thing I'm not using. I've followed all the advice previously given, but the validation just won't work.

I'm working with an Entity Framework Database-First approach and the MVVM pattern using the MVVMLight libraries. (If this has anything to do with it, I don't know.)

I've added the 'buddy' class as people have said.

public class MemberMetadata
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "Forename is required.")]
    public string Forename;
}

[MetadataType(typeof(MemberMetadata))]
public partial class Member
{
}

I've registered this class when the application loads. (In App.xaml.cs constructor)

TypeDescriptor.AddProvider(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Member), typeof(MemberMetadata)), typeof(Member));

And my binding is set like so:

<ContentControl Template="{StaticResource LabelledTextBox}" 
                            Content="Forename: " 
                            DataContext="{Binding Path=SelectedMember.Forename, 
                                          UpdateSourceTrigger=PropertyChanged, 
                                          ValidatesOnExceptions=True,
                                          NotifyOnValidationError=True, 
                                          ValidatesOnNotifyDataErrors=True,
                                          ValidatesOnDataErrors=True, 
                                          Mode=TwoWay}"/>

What else do I need to do? Or rather, how should I be doing it? Because writing 40 if statements in a method or creating a class for every validation rule I need is completely ridiculous.

1

There are 1 answers

6
Big Daddy On BEST ANSWER

In your class, add annotations to the properties and inherit from PropertyChangedNotification. Also, implement the INotifyPropertyChanged and IDataErrorInfo interfaces.