Monthly Archives: April 2015

Implementing INotifyPropertyChanged

Based on MVVM Light‘s ObservableObject:

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected ObservableObject() { }

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler == null)
        {
            return;
        }
        handler(this, e);
    }

    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    protected bool Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
        {
            return false;
        }
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}

A Visual Studio snippet for implementing properties:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>propn</Title>
        </Header>
        <Snippet>
            <Declarations>
              <Literal>
                <ID>type</ID>
                <Default>string</Default>
              </Literal>
              <Literal>
                <ID>field</ID>
                <Default>myProperty</Default>
              </Literal>
              <Literal>
                <ID>property</ID>
                <Default>MyProperty</Default>
              </Literal>
            </Declarations>
            <Code Language="csharp">
    <![CDATA[private $type$ $field$;
        public $type$ $property$
        {
            get { return $field$; }
            set { Set(ref $field$, value); }
        }]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>