Somewhat related to an old post on automatic INotifyPropertyChanged implementation via AOP here are the C# snippets that I use when writing properties that implement INotifyPropertyChanged. Talking to new users of WPF they find property change notification maybe a little bit foreign, fiddly, or possibly heavyweight. I have seen developers favour complex XAML code in favour of just using the property change interfaces available:

These constructs should be used to make your life easier. A lot of work has been done my M$ to make these perform very well so dont feel that you are using a big hammer for a little nail. These are the right tools for the job. In fact I have often seen that people find they don’t want to contaminate DTOs or Domain Entities with these properties hence the move to favour complex XAML code. This tendency is good but the wrong approach. The objects you use in your WPF application belong to the UI layer not to the domain model. If need be (and I recommend it) translate your DTOs or domain objects to entities specific to you presentation layer. This should allow you to achieve a level of separation and testability that you would not able to get from trying present domain or data transfer objects with complex XAML.

 

So anyway what this post was originally about the snippets

NotifyPropertyChanged.snippet which produces code an implementation of INotifyPropertyChanged that works with the next snippet. It is mapped to “NotifyPropertyChanged”:

#region INotifyPropertyChanged Members
/// 
/// Implicit implementation of the INotifyPropertyChanged.PropertyChanged event.
/// 
public event PropertyChangedEventHandler PropertyChanged;
/// 
/// Throws the PropertyChanged event.
/// 
/// The name of the property that was modified.
protected void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
#endregion

and the PropertyNotify.snippet that works like the standard “prop” snippet in Visual Studio. This snippet is mapped to “propNotify”:

private SomeType someValue;

public SomeType SomeValue
{
    get { return someValue;}
    set 
    { 
        if (someValue!= value)
        {
            someValue;= value;
            OnPropertyChanged("SomeValue");
        }
    }
}

 

If you have not used snippets in Visual Studio yet then you are typing too much code (or using Resharper).

*To “install”, just copy the file (it’s really an XML file with a “.snippet” extension) in your code snippets directory. By default, this is in the My Documents folder, “Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets”. *

To use just start typing either “NotifyPropertyChanged” or “propNotify” and when found hit the Tab key twice to expand them.