Search code examples
c#winformsdata-bindingcollections

How to avoid implementing INotifyPropertyChanged manually


Is there some way to avoid this. I have a lot of classes that are bound to DataGridViews and they are just simple collection of properties with default getter and setter. So these classes are very simple. Now I need to implement INotifyPropertyChanged interface for them which will increase the amount of code a lot. Is there any class that I can inherit from to avoid writing all this boring code? I image that I can inherit my classes from some class and decorate the properties with some attributes and it will do the magic. Is that possible?

I'm well aware of Aspect Oriented Programming, but I'd rather do it object oriented way.


Solution

  • Create a container base class, eg:

    abstract class Container : INotifyPropertyChanged
    {
      Dictionary<string, object> values;
    
      protected object this[string name]
      {
        get {return values[name]; }
        set 
        { 
          values[name] = value;
          PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
      }
    }
    
    class Foo : Container
    {
      public int Bar 
      {
        {get {return (int) this["Bar"]; }}
        {set { this["Bar"] = value; } }
      }
    }
    

    Note: very simplified code