As a little new year gift to myself, I thought I'd check in a change I've been working on for the WPF Starter Kit for some time now. In a nutshell, the WPF Starter Kit (http://wpfstarterkit.codeplex.com) is a great way to get started building Model View ViewModel (MVVM) based WPF applications. I made an earlier post introducing the WPS Starter Kit here: http://blogs.msdn.com/knowledgecast/archive/2009/11/02/the-wpf-starter-kit.aspx.

If you're like me and writing WPF applications using MVVM you're probably tired of defining all your view model properties like this:

/// <summary>
/// Gets/sets the route state.
/// </summary>
public RouteStatus CurrentRouteStatus
        { 
            get
            {
                return _routeStatus;
            } 
            set
            {
                _routeStatus = value;
                OnPropertyChanged("CurrentRouteStatus");
            }       
        }

Now I’ve used a base class here to eliminate some of the hassles of null-checking and raising the PropertyChanged event but it only gets us so far. One of the coolest features of C# 3.0 was automatic properties which lets you define properties like this:

/// <summary>
/// Gets/sets the route state.
/// </summary>
public RouteStatus CurrentRouteStatus { get; set; }

Unfortunately those of us using WPF (or Silverlight) data binding are hamstrung into using the old way simply because we want change notification support. I’m sure I’m not the only one who thinks that sucks big time. Well, the suckiness is over! View Models in the WPF Starter Kit now support automatic change notification on virtual properties. What this means is that provided you define your properties like this:

/// <summary>
/// Gets/sets the route state.
/// </summary>
public virtual RouteStatus CurrentRouteStatus { get; set; }

setting the property should automatically result in the PropertyChanged event being raised. The only difference here is that our property is virtual. This has no effect on how the property is used or implemented. As long as the class inherits from the WPF Starter Kit’s BaseViewModel (or the infinitely more useful UserInterfaceViewModel) it gets the benefits of automatic change notification.

The magic, in case you’re interested, happens because we use Unity (http://www.codeplex.com/unity) to inject code into the property’s setter at runtime. For more detail on how it works, you might want to explore this excellent blog post by Dmitry Shechtman. While this is not exactly how the WPF Starter Kit works, it did get me pointed in the right direction on this. I also plan to make a blog post later explaining exactly how the interception code works.

In the meantime, enjoy this new feature and the cleaner code it gets you. Happy New Year!