Jerry Nixon @Work: XAML Dev’s Favorite Snippet

Jerry Nixon on Windows

Tuesday, November 8, 2011

XAML Dev’s Favorite Snippet

Data binding in XAML is powerful. We can wire up forms without code-behind. However, for it to work, data bound objects must implement INotifyPropertyChanged. Without this interface, object property value changes are not reflected in the UI.

Objects implement properties two ways. The first method (use the snippet “prop”) is to simply create the property. We’ve all done it. It’s like this:

image

There is nothing wrong with this. We’ve used it for years. However, it doesn’t support XAML data binding. XAML data binding requires INotifyPropertyChanged. This approach (there is no snippet to use) is to raise an event when the chance occurs, like this:

image

Because we raise the event in the setter, we can’t use simplified syntax. And because there is so much typing, I am annoyed every time I write one. Why is there no snippet for this? It doesn’t matter. Let’s just make one!

Step 1 Create a New XML File

Visual Studio conveniently creates files without requiring you to save them first.

image

Step 2 COPY the Snippet Template

Give the XML file focus. Insert a snippet. The keyboard shortcut is CTRL+K, CTRL+B. From the menu select “Snippets” and “Snippet”. This will inject the snippet template.

image

You can update the orange areas and create your snippet.  For more information on creating your own snippet, look here. This is the basic template:

image

But I want to save you time. So, I write the snippet for you. You just need to copy it into your file. But, notice <Code Language=”CSharp”> This tells Visual Studio where to make the snippet available. If you make your own, remember to update this value.

Here is my snippet for you:

image
image
image

Get the real code here.

Step 3 Add the Snippet to Visual Studio

Once you have the code copied the snippet, save the file with a .snippet extension. Then use (CTRL+K, CTRL+B) to open the Snippet Manager.

image

  1. Change the Language to Visual C#
  2. Click Import and find your file
  3. Click Open and Finish

Congratulations

You now have the snippet and are ready to use it. To use your new snippet:

  1. Go to a C# file
  2. Type “propnote
  3. Type TAB+TAB
  4. Fill in the blanks, like this:

image