I am using snippet for Visual Studio, which generates a property with backup storage and an event for me. Just create an xml file called propchanged (or another name if you want) and the following contents:
<?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 in the C:\Users\YourName\Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets\ .
Then I inherit my ViewModels from some basic ViewModel that implements INotifyPropertyChanged inteface and provides a protected OnPropertyChanged method to OnPropertyChanged 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 asks you for the type and name of the property and generates code for you.
public class PersonViewModel : ViewModel { // type here 'propchanged' (or other shortcut assigned for snippet) }
UPDATE:
Another option is to generate code using an AOP framework such as PostSharp . In this case, the code will be generated and added at compile time (this way your classes will stay clean). Here is an example implementation of INotifyProperty, modified using PostSharp attributes:
[Notify] public class PersonViewModel { public Jurisdiction CountryResidence { get; set; } public Jurisdiction CountryBirth { get; set; } }
Sergey Berezovskiy
source share