MVVM设计模式基础知识--INotifyPropertyChanged接口

时间:2022-12-09 14:08:48

在.NET平台上,数据绑定是一项令人十分愉快的技术。利用数据绑定能减少代码,简化控制逻辑。
通常,可以将某个对象的一个属性绑定到一个可视化的控件上,当属性值改变时,控件上的显示数据也随之发生变化。要实现这一功能,只需要为自定义对象实现 INotifyPropertyChanged 接口即可。此接口中定义了 PropertyChanged 事件,我们只需在属性值改变时触发该事件即可.

INotifyPropertyChanged 接口是 WPF/Silverlight 开发中非常重要的接口, 它构成了 ViewModel 的基础.

INotifyPropertyChanged接口:
向客户端发出某一属性值已改变的通知

命名空间:System.ComponentModel
程序集:System(在System.dll中)
语法:public interface INotifyPropertyChanged

INotifyPropertyChanged成员:

INotifyPropertyChanged.PropertyChanged事件
在更改属性时发生

语法:event PropertyChangedEventHandler PropertyChanged

INotifyPropertyChanged 接口用于向客户端(通常是执行绑定的客户端)发出某一属性值已更改的通知。

若要在将客户端与数据源进行绑定时发出更改通知,则绑定类型应具有下列任一功能:
*实现 INotifyPropertyChanged 接口(首选)
*MVVM设计模式基础知识–INotifyPropertyChanged接口

下面的代码示例演示如何实现 INotifyPropertyChanged 接口的 PropertyChanged 事件。

// This is a simple customer class that 

// implements the IPropertyChange interface.

public class DemoCustomer : INotifyPropertyChanged
{
// These fields hold the values for the public properties.

private Guid idValue = Guid.NewGuid();
private string customerNameValue = String.Empty;
private string phoneNumberValue = String.Empty;

public event PropertyChangedEventHandler PropertyChanged;

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

// The constructor is private to enforce the factory pattern.

private DemoCustomer()
{
customerNameValue = "Customer";
phoneNumberValue = "(555)555-5555";
}

// This is the public factory method.

public static DemoCustomer CreateNewCustomer()
{
return new DemoCustomer();
}

// This property represents an ID, suitable

// for use as a primary key in a database.

public Guid ID
{
get
{
return this.idValue;
}
}

public string CustomerName
{
get
{
return this.customerNameValue;
}

set
{
if (value != this.customerNameValue)
{
this.customerNameValue = value;
NotifyPropertyChanged("CustomerName");
}
}
}

public string PhoneNumber
{
get
{
return this.phoneNumberValue;
}

set
{
if (value != this.phoneNumberValue)
{
this.phoneNumberValue = value;
NotifyPropertyChanged("PhoneNumber");
}
}
}
}