I’ve been doing a lot work with Xamarin and the excellent MvvmCross framework lately.
One thing I quickly grew tired of was writing out the ViewModel properties with the “RaisePropertyChanged” event:
1 2 3 4 5 6 7 8 9 10 |
private string _foo; public string Foo { get { return _rawContent; } set { _foo= value; RaisePropertyChanged(() => Foo); } } |
As most Visual Studio C# developers are aware, you can type “prop” or “propfull” and tab twice to generate properties automatically via Visual Studio’s snippet feature. From there, the IDE will let you tab between the data type and variable name(s) before hitting return to exit the snippet.
These are fantastic shortcuts, but MvvmCross properties will still require the “RaisePropertyChanged” function call in the setter. This can be time-consuming, especially on larger ViewModels.
I threw together a new snippet to automatically create these properties much like the existing Visual Studio snippets. See below for the entire source code of the snippet.
To install the snippet:
- Either save the below source to a file with the “.snippet” extension or clone my GitHub repo at: https://github.com/TonyLunt/mvx-prop-vs-snippet
- From there, open the Tools/Code Snippet Manager
- Use the “Import” feature to select the .snippet file.
- Inside your .cs file, type “mvxprop” and tab twice. You will now be able to populate the property in a manner similar to the “propfull” snippet.
Note: if you would like to use a different shortcut command, simply modify the “shortcut” element (line 9) in your .snippet file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?xml version="1.0" encoding="utf-8"?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>MvvmCross Viewmodel Property</Title> <Author>Tony Lunt</Author> <Description>Inserts a property with the RaisePropertyChanged call</Description> <Shortcut>mvxprop</Shortcut> </Header> <Snippet> <Code Language="CSharp"> <![CDATA[private $Type$ $PrivateFieldName$; public $Type$ $PublicPropertyName$ { get { return $PrivateFieldName$; } set { $PrivateFieldName$ = value; RaisePropertyChanged(() => $PublicPropertyName$); } }]]> </Code> <Declarations> <Literal> <ID>Type</ID> <ToolTip>Replace with type</ToolTip> <Default>Type</Default> </Literal> <Literal> <ID>PrivateFieldName</ID> <ToolTip>Replace with private field name</ToolTip> <Default>_privateField</Default> </Literal> <Literal> <ID>PublicPropertyName</ID> <ToolTip>Replace with public property name</ToolTip> <Default>PublicProperty</Default> </Literal> </Declarations> </Snippet> </CodeSnippet> </CodeSnippets> |