Implementing INotifyPropertyChanged

It's changed a lot over the years. Here is the latest iteration that I use.

   1 private BindingList<string> _Area = new BindingList<string>();
   2 public BindingList<string> Area
   3 {
   4     get => _Area;
   5     set => SetField<BindingList<string>>(ref _Area, value);
   6 }
   7 
   8 //...
   9 
  10 public event PropertyChangedEventHandler PropertyChanged;
  11 
  12 protected void SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
  13 {
  14     field = value;
  15     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  16 }

Suppose that the value you are setting with SetField is a property of a Model object. You may get an error that says, "A non ref-returning property or indexer may not be used as an out or ref value." There is an easy fix for this.

private BindingList<string> _Area = new BindingList<string>();
public BindingList<string> Area
{
    get => _Area;
    set => _Area = SetField<BindingList<string>>(value);
}

//...

public event PropertyChangedEventHandler PropertyChanged;

protected void SetField<T>(T value, [CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    return value;
}

ProgrammingLinks/INotifyPropertyChanged (last edited 2023-09-14 23:04:09 by scot)