静态变量的 INotifyPropertyChanged [英] INotifyPropertyChanged for static variable

查看:39
本文介绍了静态变量的 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;

这篇关于静态变量的 INotifyPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆