Creating code snippets is one of those things I’ve left to learn later a lot of times… until today that I had to create an object with more than thirty properties launching the PropertyChanged event and I couldn’t delay it further.
To increase my productivity I have wasted a little of time and I have created a code snippet for the properties implementing the INotifyPropertyChanged. I’ve called it propNot
To do so, in Visual Studio, I went to Tools and from there to Code Snippets Manager. There I chose C# and then I copied the address of the My Code Snippets folder.
I created a .snippet file on that folder with this content
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>propNot</Title>
<Shortcut>propNot</Shortcut>
<Description>Code snippet for properties with NotifyPropertyChanged</Description>
<Author>Chan</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>privName</ID>
<Default>privName</Default>
<ToolTip>Private name of the property</ToolTip>
</Literal>
<Literal>
<ID>pubName</ID>
<Default>pubName</Default>
<ToolTip>Public name of the property</ToolTip>
</Literal>
<Literal>
<ID>type</ID>
<Default>string</Default>
<ToolTip>Type of the property</ToolTip>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[private $type$ $privName$;
public $type$ $pubName$
{
get { return $privName$; }
set
{
$privName$ = value;
// Call NotifyPropertyChanged when the property is updated
NotifyPropertyChanged("$pubName$");
}
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>It’s tested and working, both the TwoWay binding and the Code Snippet.Now that I know how to do them I think I’ll do them really usually. --EDIT-- I lied, I don't do them that usually because I am VERY lazy, but I do use this other snippet a lot:
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>INotify region with the necessary methods to implement the interface</Title>
<Shortcut>inotifyregion</Shortcut>
<Description>Creates region with the necessary methods to implement the interface INotifyPropertyChanged</Description>
<Author>Jose Sanchez</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations />
<Code Language="csharp"><![CDATA[#region INotifyMethods
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void NotifyPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>





No comments:
Post a Comment