If I’ve written code around PropertyChanged notification in Visual Studio once then I must have done it thousands of times so I thought I’d do a quick snippet and drop it here.
Snippet for a class that implements INotifyPropertyChanged;
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Class with property changed notification</Title>
<Shortcut>pcclass</Shortcut>
<Description>Code snippet for class with property changed notification</Description>
<Author>Mike Taulty</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Imports>
<Import>
<Namespace>System.ComponentModel</Namespace>
</Import>
</Imports>
<Declarations>
<Literal>
<ID>name</ID>
<ToolTip>Class name</ToolTip>
<Default>MyClass</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[public class $name$ : INotifyPropertyChanged
{
$selected$$end$
protected void FirePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
and a snippet for a property within that kind of class;
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>prop</Title>
<Shortcut>propch</Shortcut>
<Description>Code snippet for a property with notification</Description>
<Author>Mike Taulty</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[
public $type$ $property$
{
get
{
return(_$property$);
}
set
{
_$property$ = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("$property$"));
}
}
}
$type$ _$property$;
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
hopefully I can avoid writing that explicitly ever again.
I appreciate that sometimes you might want to implement the property changed stuff in a base class (and sometimes you won’t) and there are fancier solutions around reflection and so on but I’m one for keeping-it-simple here 🙂