您的位置:首页 > 运维架构

通过 INotifyPropertyChanged 实现观察者模式

2013-09-25 14:49 417 查看
INotifyPropertyChanged它的作用:向客户端发出某一属性值已更改的通知。当属性改变时,它可以通知客户端,并进行界面数据更新.而我们不用写很多复杂的代码来更新界面数据,这样可以做到方法简洁而清晰,松耦合和让方法变得更通用.可用的地方太多了:例如上传进度,实时后台数据变更等地方。它的作用:向客户端发出某一属性值已更改的通知。当属性改变时,它可以通知客户端,并进行界面数据更新.而我们不用写很多复杂的代码来更新界面数据,这样可以做到方法简洁而清晰,松耦合和让方法变得更通用.可用的地方太多了:例如上传进度,实时后台数据变更等地方.目前我发现winform和silverlight都支持,确实是一个强大的接口.

public class DemoCustomer1 : PropertyChangedBase
{
// These fields hold the values for the public properties.
private Guid idValue = Guid.NewGuid();
private string customerNameValue = String.Empty;
private string phoneNumberValue = String.Empty;

// The constructor is private to enforce the factory pattern.
private DemoCustomer1()
{
customerNameValue = "Customer";
phoneNumberValue = "(555)555-5555";
}

// This is the public factory method.
public static DemoCustomer1 CreateNewCustomer()
{
return new DemoCustomer1();
}

// 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;
this.NotifyPropertyChanged(p => p.CustomerName);
//NotifyPropertyChanged("CustomerName");
}
}
}

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

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

/// <summary>
/// 基类
/// </summary>
public class PropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

/// <summary>
/// 扩展方法
/// </summary>
public static class PropertyChangedBaseEx
{
public static void NotifyPropertyChanged<T, TProperty>(this T propertyChangedBase, Expression<Func<T, TProperty>> expression) where T : PropertyChangedBase
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression != null)
{
string propertyName = memberExpression.Member.Name;
propertyChangedBase.NotifyPropertyChanged(propertyName);
}
else
throw new NotImplementedException();
}
}View CodeView Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: