INotifyPropertyChanged用于静态变量

我有一个非静态的变量,并且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中,他们为静态属性引入了属性更改机制:

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

 public static event EventHandler MyPropertyChanged; public static event EventHandler StaticPropertyChanged; 

非常好的例子,当我想将一些属性在线绑定到组件时,我将它用于应用程序中的一些常规设置

  public sealed class DataGridClass:INotifyPropertyChanged { private static readonly DataGridClass instance = new DataGridClass(); private DataGridClass() { } public static DataGridClass Instance { get { return instance; } } private int _DataGridFontSize {get;set;} public int DataGridFontSize { get { return _DataGridFontSize; } set { _DataGridFontSize = value; RaisePropertyChanged("DataGridFontSize"); } } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } 

设置启动属性:

 DataGridClass.Instance.DataGridFontSize = 14(or read from xml) 

将此绑定到组件属性

 xmlns:static="clr-namespace:MyProject.Static"     

当您在应用程序中的某个位置更改此值,如“首选项” – > DataGrid FontSize – 它会自动更新此属性以使用UpdateSourceTrigger绑定

  private void comboBoxFontSize_DropDownClosed(object sender, EventArgs e) { DataGridClass.Instance.DataGridFontSize = Convert.ToInt32(comboBoxFontSize.Text); }