Michael Haddad
Michael Haddad

Reputation: 4435

How to create a property changed event when the property has only a getter in C#

Let's say I have this class (which is really for demonstration purposes):

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string IdNumber { get; set; }

    // CheckPopulationRegistry() checks against the database if a person
    // these exact properties (FirstName, LastName, IdNumber etc.) exists.
    public bool IsRealPerson => CheckPopulationRegistry(this);
}

I want to be notified when IsRealPerson is changed.

Usually, I would implement the INotifyPropertyChanged interface, but then I'd need to create an OnIsRealPersonChanged() method, and call it from the setter, which I do not have.

Ideas?

Upvotes: 3

Views: 3989

Answers (1)

Dennis
Dennis

Reputation: 37770

You need something like this:

public class Person : INotifyPropertyChanged
{
    private string firstName;
    private string lastName;

    private void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private bool CheckPopulationRegistry(Person p)
    {
        // TODO:
        return false;
    }

    public string FirstName
    {
        get { return firstName; }
        set
        {
            if (firstName != value)
            {
                firstName = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(IsRealPerson));
            }
        }
    }

    public string LastName
    {
        get { return lastName; }
        set
        {
            if (lastName != value)
            {
                lastName = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(IsRealPerson));
            }
        }
    }

    // IdNumber is omitted

    public bool IsRealPerson => CheckPopulationRegistry(this);

    public event PropertyChangedEventHandler PropertyChanged;

}

Upvotes: 1

Related Questions