Skip to content

On_PropertyName_Changed

Lucas Trzesniewski edited this page Nov 4, 2021 · 7 revisions

Allows having a "similar named" method called when a property is set

Your code

    public class Person : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;

      public string Name { get; set; }

      public void OnNameChanged()
      {
        Debug.WriteLine("Name Changed");
      }
    }

What gets compiled

Note the call to OnNameChanged injected in the setter of the property.

    public class Person : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;

      string name;

      public string Name
      {
        get { return name; }
        set
        {
          if (value != name)
          {
            name = value;
            OnNameChanged();
            OnPropertyChanged("Name");
          }
        }
      }

      public void OnNameChanged()
      {
        Debug.WriteLine("Name Changed");
      }

      public virtual void OnPropertyChanged(string propertyName)
      {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
    }

"Referencing" the On_PropertyName_Changed method by attribute

To make usage more clearer, avoid "method is never used" warnings, or allow individual method names, you can link the property and the change method via the OnChangedMethod attribute:

    public class Person : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;

      [OnChangedMethod(nameof(OnMyNameChanged))]
      public string Name { get; set; }

      private void OnMyNameChanged()
      {
        Debug.WriteLine("Name changed");
      }
    }

Passing old and new value to the On_PropertyName_Changed method

To access the old and new value in the On_PropertyName_Changed method, the following signature is supported:

    public class Person : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;

      [OnChangedMethod(nameof(OnName1Changed))]
      public string Name1 { get; set; }

      private void OnName1Changed(object oldValue, object newValue)
      {
        Debug.WriteLine("Name Changed:" + oldValue + " => " + newValue);
      }

      [OnChangedMethod(nameof(OnName2Changed))]
      public string Name2 { get; set; }

      private void OnName2Changed(string oldValue, string newValue)
      {
        Debug.WriteLine("Name Changed:" + oldValue + " => " + newValue);
      }
    }

The parameters of the On_PropertyName_Changed can be object or the same as the properties type. However both parameters must be of the same type.