I’ve been using the a new code snippet to create an ‘observable’ property when working with WPF and the Model-View-ViewModel pattern. This is really only useful if your class implements INotifyPropertyChanged, which our ViewModel base does.
The snippet generates the following block of code:
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
..and here is the snippet. See my previous post on [DataMember] Code Snippet on how to install snippets.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>oprop</Title>
<Shortcut>oprop</Shortcut>
<Description>Code snippet for an automatically implemented observable property for any class that implements INotifyPropertyChanged.</Description>
<Author>Your name here</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>field</ID>
<ToolTip>Backing Field Name</ToolTip>
<Default>_myProperty</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[
private $type$ $field$;
public $type$ $property$
{
get
{
return $field$;
}
set
{
if ( $field$ != value )
{
$field$ = value;
OnPropertyChanged("$property$");
}
}
}
$end$
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>