Thanks to everyone who came along to my DEV311 at TechEd New Zealand yesterday. Here’s the low down on the snippets demo that didn’t work the way it should on the day …

Notifying Properties

Creating a property that triggers the PropertyChanged event isn’t difficult, but it is mindless boilerplate. The propn snippet makes it really easy to write with just a few keystrokes.

Here’s the output of using the snippet to declare a FullName property:

public string FullName
{
    get { return mFullName; }
    set
    {
        if (!Object.Equals(mFullName, value))
        {
            mFullName = value;
            OnPropertyChanged();
        }
    }
}

private string mFullName;

Note that this is triggering the OnPropertyChanged() method with no parameters, expecting it to use the new [CallerMemberName] attribute introduced in .NET 4.5.

INotifyPropertyChanged Implementation

The supporting infrastructure for the INotifyPropertyChanged event is also boilerplate - hence the notify snippet that produces this code:

public event PropertyChangedEventHandler PropertyChanged
{
    add { mPropertyChanged += value; }
    remove { mPropertyChanged -= value; }
}

private void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
    var handlers = mPropertyChanged;
    if (handlers != null)
    {
        handlers(this, new PropertyChangedEventArgs(propertyName));
    }
}

private PropertyChangedEventHandler mPropertyChanged;

Between notify and propn, writing the infrastructure to support databinding is a whole lot easier.

Comments

blog comments powered by Disqus