INotifyPropertyChanged for static variable

Shibli picture Shibli · Mar 20, 2012 · Viewed 13.2k times · Source

I had a variable which was not static and INotifyPropertyChanged implemented succesfully. Then I tried to make it global, so turned it a static variable. But this time, INotifyPropertyChanged does not work. Any solution?

Answer

mmix picture mmix · Mar 20, 2012

INotifyPropertyChanged works on instance properties. One solution is to use a singleton pattern and keep INotifyPropertyChanged, the other is to use your own event to notify listeners.

Singleton example

public sealed class MyClass: INotifyPropertyChanged
{
   private static readonly MyClass instance = new MyClass();
   private MyClass() {}

   public static MyClass Instance
   {
      get 
      {
         return instance; 
      }
   }

   // notifying property
   private string privMyProp;
   public string MyProp
   {
       get { return this.privMyProp; }

       set
       {
           if (value != this.privMyProp)
           {
               this.privMyProp = value;
               NotifyPropertyChanged("MyProp");
           }
       }
   }


   // INotifyPropertyChanged implementation
   public event PropertyChangedEventHandler PropertyChanged;

   private void NotifyPropertyChanged(String info)
   {
       var handler = PropertyChanged;
       if (handler != null)
       {
           handler(this, new PropertyChangedEventArgs(info));
       }
   }
}

EDIT: In WPF 4.5, they introduced property changed mechanic for static properties:

You can use static properties as the source of a data binding. The data binding engine recognizes when the property's value changes if a static event is raised. For example, if the class SomeClass defines a static property called MyProperty, SomeClass can define a static event that is raised when the value of MyProperty changes. The static event can use either of the following signatures.

public static event EventHandler MyPropertyChanged;
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;