This blog post is a part of Luis Matos’s Xamarin Month, where this months topic is Code Snippets. For more information take a look at this blog and see the list of all the other authors who are participating. There you can find a lot of cool snippets to speed-up your development process.
What are code snippets?
Code snippets are small blocks of reusable code that can be inserted in a code file using a right-click menu (context menu) command or a combination of hotkeys. They typically contain commonly used code blocks such as
if-else blocks, but they can be used to insert entire classes or methods.
How to install a snippet?
I want to show you how you can easily adds the custom snippets to Visual Studio on Windows. You need to open
Tools > Code Snippet Manager.
Now you can press the Import button and select all your snippets you want to add.
Now mark all your code snippets (you can see the small blue check mark in the corner) and select your code snippets folder on the right. Press Finish and all the snippets are imported you can start using them directly.
My code snippets
Now let’s take a look at some of my snippets I’m using during app development.
My first snippets has the shortcode dwl and creates a
Debug.WriteLine containing the class name, the method name, and an optional message.
If your are working with MVVM you need to call
OnPropertyChanged for your properties to inform the UI if the data has changed. The snippet with the shortcode fprop creates exactly such a property calling
OnPropertyChanged ìn the setter.
To save some time while creating new commands within your ViewModel I’ve created the snippet with the shortcode icmd to create such a command.
While creating custom controls you need to provide bindable properties so that you are able to bind properties to your control. For this task the snippet with the shortcode bprop prepares such a bindable property for you.
You are also able to create XAML snippets. So the snippet with the shortcode istyle creates a new implicit style resource. You simple need to change the TargetType and start adding new setter by using the setter snippet.
Like istyle you can create with the snippet estyle a new explicit style resource. So you also need to provide a name for your style.
You can easily extend your library with useful code snippets. I hope that you can use some of mine in your upcoming projects.