wpfvalidationmvvm

MVVM Toolkit Data Validation and ObservableProperty


I'm working in WPF and using the MVVM community toolkit. Reading the documentation, I understand that I can make validation work by inheriting from ObservableValidator and using this pattern for my bound properties:

    private string name;

    [Required(ErrorMessage = "You must enter a name.")]
    [MinLength(2)]
    [MaxLength(100)]
    public string Name
    {
        get => name;
        set => SetProperty(ref name, value, true);
    }

Using this pattern, I can get a red box around the field and can display the error message on my UI.

Using this pattern though, I lose the source generator goodness of the [ObservableProperty], for example I don't get an auto generated OnNameChanged() partial that I can tap into.

Am I missing something? Is there a way to get the source generator goodness of the [ObservableProperty] and the [ObservableValidator] together?

I've tried simply converting my [ObservableProperty] to full property and immediately got an error on the associated OnNameChanged() property, so if it's possible to have both then there is a step I'm missing and can't find in the documentation.

Thanks in advance for your help. Cheers Mike


Solution

  • Add [NotifyDataErrorInfo] to your private field:

    public partial class  ViewModel : ObservableValidator
    {
       [NotifyDataErrorInfo]
       [MinLength(2)]
       [MaxLength(100)]
       [ObservableProperty]
       private string name;
    }