3

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?

Community
  • 1
  • 1
Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • 1
    Whatever logic is changing output of CheckPopulationRegistry(), raise the PropertyChanged event from there before returning out of the method. – Nitin Oct 27 '16 at 09:23
  • _need to create an OnIsRealPersonChanged()_ - that's unusual. The norm is just an `OnPropertyChanged(string propertyname)`. – H H Oct 27 '16 at 09:23
  • set { IsRealPerson = value; CallSomeMethod(); } – Vivek Nuna Oct 27 '16 at 09:24

1 Answers1

1

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;

}
Dennis
  • 37,026
  • 10
  • 82
  • 150