Share via


Windows 8 ViewModel Property Code Snippet

Visual Studio provides a bunch of good code snippets for creating boilerplate code. For example if you type “prop” you get this in intellisense

 

image

You’ll see a few nice property snippets.

  • prop – creates a basic automatic property
  • propa – creates an attached property
  • propdp – creates a dependency property
  • propfull – creates a public property with a private backing field
  • propg – creates a basic automatic property but the set is marked private

I use these constantly but hit an issue when building my Windows 8 apps. For ViewModels in Windows 8, the default templates take advantage of a wonderful attribute CallerMemberName in the OnPropertyChanged method of the ViewModel base class. This allows you to create properties that support notifications in a very simple manner. Like this

image

But that pattern doesn’t have code snippet. That’s easy to fix though. I created my own snippet to generate that type of property and named it proprt.

Just create a file called proprt.snippet in the folder [USERPROFILE]\Documents\Visual Studio 2012\Code Snippets\Visual C#\My Code Snippets

It should have the following contents

 <?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="https://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>proprt</Title>
            <Shortcut>proprt</Shortcut>
            <Description>Code snippet for property and backing field with change notification in Windows Runtime view models</Description>
            <Author>Microsoft Corporation</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property type</ToolTip>
                    <Default>int</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 { this.SetProperty(ref this.$field$, value); }
    }
    $end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Then you should see it show up in the Visual Studio Code Snippet Manager under My Code Snippets

image

Voila, start creating properties with it and build your Windows 8 Store apps even easier!