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:
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:
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.
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.
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:
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:
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.
- Change the Language to Visual C#
- Click Import and find your file
- Click Open and Finish
You now have the snippet and are ready to use it. To use your new snippet:
- Go to a C# file
- Type “propnote”
- Type TAB+TAB
- Fill in the blanks, like this:
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)