Monday, March 17, 2014

WPF 4.5: Binding and change notification for static properties

One of the new features in WPF 4.5 is support for binding to static properties. In addition to the binding syntax itself, there's new support for static property change notification. In many cases, it is still advisable to use a Singleton pattern or another approach for binding. However, there are cases when your application design requires binding to static properties. In those cases, WPF should kindly step out of the way and let you accomplish your task the way you've architected it.

Two Approaches to Change Notification

There are two ways to notify the binding system of property changes, both of which follow the same pattern as their instance-based relatives.

public static class AppSettings
    public static event EventHandler StorageFolderChanged;
    private static string _storageFolder;
    public static string StorageFolder
        get { return _storageFolder; }
            if (value != _storageFolder)
                _storageFolder = value;
                if (StorageFolderChanged != null)
                    StorageFolderChanged(null, EventArgs.Empty);

The static property name in this example is StorageFolder. The event name is therefore StorageFolderChanged. Note that nothing useful is passed as part of the event - there's no instance to provide and no event args. The second approach is to create a single event which is the static version of the INPC PropertyChanged event named StaticPropertyChanged. This requires using the System.ComponentModel namespace to pull in the PropertyChangedEventArgs definition.

Read more: