As you can read in the last couple of posts (like this, or this), I've been working with WPF for the last couple of weeks. Not very fun.

I'm doing mostly the VMs and that involves a lot of property change notifications. We use the MVVMLight toolkit for basic MVVM tasks, like having base class for property change notification.

As a result, all our ViewModels inherit from the BindableBase and inherit a method called SetProperty() that invokes the PropertyChanged event. Our properties look mostly like this:

private string userName;
public string UserName
{
  get => userName;
  set => SetProperty(ref userName, value);
}

And we write this a lot. And I mean, a lot. So it occured to me: if there's a prop snippet for the auto-property and a propfull for the full property, a propg for autoproperties with private setters and a propdp for dependency properties, why not have a snippet for this? Like propb, where b stands for "bound", in my head.

So, I created one :) Feel free to save this into a text file with the snippet extension, and then load it into the Snippet Manager in Visual Studio ;)

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>propb</Title>
			<Shortcut>propb</Shortcut>
			<Description>Code snippet for property with INotifyPropertyChanged support</Description>
			<Author>Akos Nagy</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>
				<Literal>
					<ID>changemethod</ID>
					<ToolTip>The method responsible for setting the field value and firing INotifyPropertyChanged</ToolTip>
					<Default>SetProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[private $type$ $field$;

	public $type$ $property$
	{
		get => $field$;
		set => $changemethod$(ref $field$, value);
	}
	$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

It works kinda like the propfull; you can use TAB to jump from the field type to the field name to the property name, and the respective names and types are bound together. And it also allows you to specify the name of the property setter/INotifyPropertyChanged invoker method with an extra TAB.

Code snippet for databound properties in MVVM
Share this

© 2018. All Rights Reserved.

Falconium theme based on Ghostium Theme

Proudly published with Ghost