Code snippet for databound properties in MVVM

Akos Nagy
Apr 15, 2018

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="">
	<CodeSnippet Format="1.0.0">
			<Description>Code snippet for property with INotifyPropertyChanged support</Description>
			<Author>Akos Nagy</Author>
					<ToolTip>Property type</ToolTip>
					<ToolTip>Property name</ToolTip>
					<ToolTip>The variable backing this property</ToolTip>
					<ToolTip>The method responsible for setting the field value and firing INotifyPropertyChanged</ToolTip>
			<Code Language="csharp"><![CDATA[private $type$ $field$;

	public $type$ $property$
		get => $field$;
		set => $changemethod$(ref $field$, value);

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.

Akos Nagy
Posted in Visual Studio WPF