Every time I go to write an MVVM application (say every 4-6 months) I rewrite my ViewModelBase
class. This is for a range of reasons but let's say either I don't have access to prior code, the previous code was built for a client and isn't my code, or I'm working on someone else's machine and still don't have the code.
So I rewrite the basic INotifyPropertyChanged
implementation, and I think it's a little different each time. Here's what I've come up with today:
public class ViewModelBase : INotifyPropertyChanged
{
protected void OnPropertyChanged<T>(Expression<Func<T>> expression)
{
var property = (MemberExpression)expression.Body;
this.OnPropertyChanged(property.Member.Name);
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
I would like to get a nice implementation that is simple and small, and any improvements to this (what other functionality is required in a ViewModelBase
?) would be great.