INotifyPropertyChanged用于静态变量

问题描述:

我有一个不是静态的变量,并且成功实现了INotifyPropertyChanged。然后,我尝试将其设置为全局,因此将其设置为静态变量。但是这次,INotifyPropertyChanged不起作用。有解决方案吗?

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?

INotifyPropertyChanged 适用于实例属性。一种解决方案是使用单例模式并保留 INotifyPropertyChanged ,另一种解决方案是使用您自己的事件来通知侦听器。

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.

单个示例

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));
       }
   }
}

编辑:在WPF 4.5中,他们为静态属性引入了属性更改机制:

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


您可以将静态属性用作数据绑定的源。如果引发
静态事件,则
数据绑定引擎会识别属性值何时更改。例如,如果类SomeClass定义了名为MyProperty的
静态属性,则SomeClass可以定义当MyProperty的值更改时引发的静态事件
。静态事件
可以使用以下任一签名。

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;