Thursday, 29 October 2009

Code Snippets for INotifyPropertyChanged

The INotifyPropertyChanged interface is one of the mechanisms available to update WPF bindings when a property value changes.

If you work with the Model-View-ViewModel pattern, you probably implement INotifyPropertyChanged in your ViewModel classes.

To help myself create properties with support for INotifyPropertyChanged, I created a couple of simple code snippets with literal replacements for the property name and type.

Click here to download and install the snippets.

The snippets

The first snippet (shortcut inpc) provides a barebones implementation of INotifyPropertyChanged:

#region INotifyPropertyChanged support

protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}

public event PropertyChangedEventHandler PropertyChanged;

#endregion


You’d probably want to put the above into a base class to save repetition. You don’t have to use this implementation, but the second snippet calls OnPropertyChanged,  so you need a compatible function available.



If you want to add some validation on the propertyName parameter, remember that null and String.Empty are legitimate values.



The second snippet (shortcut propn)  implements a property with a backing field and a call to OnPropertyChanged when the value of the property is set:



public int MyProperty
{
get
{
return m_MyProperty;
}
set
{
m_MyProperty = value;
OnPropertyChanged("MyProperty");
}
}
int m_MyProperty;

No comments:

Post a Comment