Skip to content
This repository has been archived by the owner on Apr 2, 2024. It is now read-only.

ViewModel with bindable properties and validation

David Sungaila edited this page Sep 18, 2020 · 1 revision

Let your class derive from PresentationBase.ViewModel. Create a backing field and make sure your property setter calls SetProperty.

Your function validates the given value and returns an IEnumerable<string> with found validation errors. Return null or an empty collection if the validation succeeds.

public class AwesomeViewModel : ViewModel
{
    private string _name;

    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value, NameValidation);
    }

    private IEnumerable<string> NameValidation(string value)
    {
        if (string.IsNullOrEmpty(value))
            yield return "Name cannot be null or empty!";
        else if (value == "sungaila")
            yield return "Name cannot be stupid!";
    }
}