在博客“MVVM设计模式基础知识–INotifyPropertyChanged接口”一文中,已经谈到了INotifyPropertyChanged接口。
今天我们来谈一下NotificationObject类。
设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。 毫无疑问,设计模式于己于他人于系统都是多赢的;设计模式使代码编制真正工程化;设计模式是软件工程的基石脉络,如同大厦的结构一样。
但是设计模式不是一成不变的,每个人的理解也有所不同。譬如说MVVM设计模式,如果不需要ICommand接口,很多人就习惯将Model和ViewModel合二为一。这次很多人会采用的是继承NotificationObect类而不是继承INotifyPropertyChanged接口。
譬如说在Prism框架(Prism是一个超轻量的开源框架,前身是Angel ,现在改名为 Prism)中,有一个NotificationChanged类,位于Microsoft.Practices.Prism.ViewModel命名空间下,而NotificationObject类是继承INotifyPropertyChanged接口。
下面通过.NET Reflector查看Microsoft.Practices.Prism.ViewModel中的NotificationObject类。
源码如下:
public abstract class NotificationObject : INotifyPropertyChanged
{
// Events
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
// Methods
protected NotificationObject()
{
}
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
string propertyName = PropertySupport.ExtractPropertyName<T>(propertyExpression);
this.RaisePropertyChanged(propertyName);
}
protected virtual void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected void RaisePropertyChanged(params string[] propertyNames)
{
if (propertyNames == null)
{
throw new ArgumentNullException("propertyNames");
}
foreach (string str in propertyNames)
{
this.RaisePropertyChanged(str);
}
}
}
NotificationObject类的使用:
public class PatientInfoViewModel : NotificationObject
{
public static string m_PatID = "";
public string PatID
{
get { return m_PatID; }
set
{
if (!value.Equals(m_PatID))
{
m_PatID = value;
this.RaisePropertyChanged(() => this.PatID);
}
}
}
}