0
votes

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
See my update for IDataErrorInfo. - Big Daddy
this is how I've done validation in my WPF app. No IDataErrorInfo needed. - XAMlMAX
@XAMIMAX, I did look at doing it like that, but I would have ended up with about 20 to 30 classes because of that. Surely that's a bad idea... - Jake
DataAnnotations only work when someone wrote code looking for them. Binding validation in the UI is a poor substitute for IDataErrorInfo. Validation is a business concern, anyhow, and so shouldn't sit in your UI. You can write your own base class that accesses DAAs on your properties and uses them to perform validation. I'm pretty sure others have done the same, so you can snag some code somewhere. I think I've done it in the past... - user1228

1 Answers

0
votes

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