INotifyPropertyChanged

INotifyPropertyChanged

This question already has answers here:
Binding to static property

(12个答案)


在4个月前关闭。




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

最佳答案

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

单例示例

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中,他们为静态属性引入了属性更改机制:


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

关于c# - INotifyPropertyChanged用于静态变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9786519/

10-12 00:26