This code snippet extends the functionality found in prop code snippet. It will populate the backing field in the property, check for equality in the setter and call PropertyChanged. It assumes you have a base class that handles the implementation of INotifyPropertyChanged.
When the snippet is called, it will generate code that looks like this:
private int myVar;
public int MyProperty
{
get { return myVar; }
set
{
if (!myVar.Equals(value))
{
myVar = value;
base.OnPropertyChanged("MyProperty");
}
}
}
To use this snippet, create a new text file at:
C:\users\<your user name>\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets
Call it “propINP.snippet”
Populate the contents of the file with this:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>propINP</Title>
<Author>Microsoft Corporation</Author>
<Description>Code snippet for property and backing field and INotifyPropertyChanged</Description>
<HelpUrl>
</HelpUrl>
<Shortcut>propINP</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal Editable="true">
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
<Function>
</Function>
</Literal>
<Literal Editable="true">
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
<Function>
</Function>
</Literal>
<Literal Editable="true">
<ID>field</ID>
<ToolTip>The variable backing this property</ToolTip>
<Default>myVar</Default>
<Function>
</Function>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[private $type$ $field$;
public $type$ $property$
{
get { return $field$;}
set
{
if(!$field$.Equals(value))
{
$field$ = value;
base.OnPropertyChanged("$property$");
}
}
}
$end$]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>