I have written an abstract View Model which all my other View Models inherit when I write any apps in Silverlight, WinRT, WPF etc. The class was written to attempt to address an issue I have run into frequently. That is, after refactoring code, all my property names are wrong and I often forget to rename them. Debugging by identifying views which don't reflect their view models is hard, thus this.
The idea is relatively simple. It provides an implementation of the INotifyPropertyChanged interface with the addition of some additional safety checking when debugging the project. This is done via reflection by checking if the property you are attempting to notify actually exists.
Thus:
class Foo : AbstractViewModel {
public object Bar { get; set; }
}
Will throw an exception if I try to call NotifyPropertyChanged("Ponies") since Ponies is not a property in Foo.
The AbstractViewModel looks like this:
using System;
using System.ComponentModel;
#if DEBUG
// We need reflection in order to debug our Property Changed Notifications
using System.Reflection;
#endif
namespace WorldOfZero.Common.ViewModels
{
public class AbstractViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string name)
{
#if DEBUG
// This will detect and throw an error if we attempt to Notify a change on a none existant property.
// This helps eliminate stupid mistakes like spelling errors.
// This code is only included in the debug builds of the app, this prevents us from slowing down production code.
Type type = this.GetType();
PropertyInfo property = type.GetRuntimeProperty(name);
if (property == null)
{
throw new InvalidOperationException(String.Format("Attempting to Notify a change on a property ({0}) that does not exist.", name));
}
#endif
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}
I'm looking for ways to improve this. I'm also curious if there might be better ways to solve this than with Reflection.