I use snippet for Visual Studio, which generates property with backing storage and event raising for me. Simply create xml file with name propchanged
(or other name, if you wish) and following content:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>propchanged</Title>
<Shortcut>propchanged</Shortcut>
<Description>Code snippet for property (with call to OnPropertyChanged) and backing field</Description>
<Author>lazyberezovsky</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>string</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
</Literal>
<Literal>
<ID>field</ID>
<ToolTip>The variable backing this property</ToolTip>
<Default>myVar</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[private $type$ $field$;
public $type$ $property$
{
get { return $field$;}
set
{
if ($field$ == value)
return;
$field$ = value;
OnPropertyChanged("$property$");
}
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
And put it to folder C:\Users\YourName\Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets\
.
Next, I inherit my ViewModels from some base ViewModel, which implements INotifyPropertyChanged
inteface and provides protected method OnPropertyChanged
for generating `PropertyChanged' event.
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
}
Now when you type propchanged
in Visual Studio, it will ask you for property type and name, and generate code for you.
public class PersonViewModel : ViewModel
{
// type here 'propchanged' (or other shortcut assigned for snippet)
}
UPDATE:
Another option is generating code by AOP framework like PostSharp. In this case code will be generated and added during compilation (thus your classes will stay clean). Here is example of implementing INotifyProperty changed via PostSharp attributes:
[Notify]
public class PersonViewModel
{
public Jurisdiction CountryResidence { get; set; }
public Jurisdiction CountryBirth { get; set; }
}