Pro Tip: Useful Code Snippets For Your Xamarin.Forms Development

Code snippets are a hidden gem in Visual Studio that most of us do not pay much attention to. Utilizing them correctly can increase productivity when we have a lot to code. In Visual Studio, code snippets are available for multiple programming languages e.g. C#, F#, XML, HTML, CSS, Python, etc. They are extremely useful when we have a bunch of boiler plate code for our properties, constructors, bindable properties, etc.

Code snippets can be a huge topic, but in this post, I will list some of the XAML and C# code snippets useful when developing Xamarin.Forms mobile applications.

In this post,

  • Snippets
  • Creating Code Snippets
  • C# Examples
  • XAML Examples
  • Export Templates


Note: Snippets in this post are created in Visual Studio for Mac, but they should work in Visual Studio on Windows as well.

Snippets

Code snippet templates are XML files that hold snippet definition,

snippet_def

These definitions can be imported and exported (see end of this blog) to be reused and distributed.

Creating Code Snippets

To create a code snippet, go to Visual Studio > Preferences > Code Snippets,

preferences

You will find a lot of built-in snippets that you may or may not have used yet. It is a good idea to look at some of the existing snippets to find out how they are setup. A snippet has several parts that require setup,

parts

  • Shortcut: the keyword to type when requesting this snippet
  • Group: the language this snippet is used in. You can have snippets a number of supported languages e.g. C#, Html, XML, Python, Razor, CSS, F#, etc.
  • Description: short description of what this snippet will generate
  • Mime: to support the language in the group
  • Is expandable template: Will expand from the point of insertion (cursor).
  • Is surround with template: If this template will surround the selected code/text.
  • Template Text: code snippet goes in this area

and a property pane for items in the code snippet. There are several code snippet functions available to get some run-time information for the items in the snippet.

C# Examples

Here is a list of code snippets that can be useful if setup correctly.

1. Constructors


If you have a base view model that expects something in the constructor, you will have to type a lot for each derived base view model. You can get a snippet to fill most of the code for you,

public SomeClass(IServiceA serviceA, IServiceB serviceB) {}

or pass a parameter to base,

public SomeClass(IServiceA serviceA,  IServiceB serviceB) : base (serviceB) {}

or make it flexible with $service$ variable,

public SomeClass(I$service$ $service$) : base ($service$) {}

Template:

Shortcut: sctor
Group: C#
Description: Constructor with Services Template
Mime: text/x-csharp

$modifier$$classname$ (I$service$ $service$) : base($service$)
{
     $end$
}

$modifier$ – use GetConstructorModifier() function to get the modifier for the class.
$classname$ – use GetCurrentClassName() function to get the name of the class.
$service$ – Name of the service to be injected.

2. Bindable Properties


One of the my most used snippet is the bindable properties.

Template:

 public static BindableProperty $some$Property = BindableProperty.Create(nameof($some$), typeof($type$), typeof($classname$));
 public $type$ $some$
 {
  get { return ($type$) GetValue($some$Property); }
  set { SetValue($some$Property, value); }
 }

$some$ – name of the property.
$type$ – type of the property.
$classname$ – use GetCurrentClassName() to get the name of the class.

Usage:

bprop

3. INotifyPropertyChanged


When using INotifyPropertyChanged,

private $type$ $fieldName$;
public $type$ $propertyName$
{
    get { return $fieldName$; }
    set 
    { 
        $fieldName$ = value;
        OnPropertyChanged(nameof($propertyName)); 
    }
}$end$

$type$ – type of the property.
$fieldName$ – backing field name.
$propertyName$ – Property name.

4. Prism.Forms SetProperty()


Property

 private $type$ $fieldName$;
 public $type$ $propertyName$
 {
     get { return $fieldName$; }
     set { SetProperty(ref $fieldName$, value); }
 }$end$

$type$ – type of the property.
$fieldName$ – backing field name.
$propertyName$ – Property name.

XAML Examples

1. Grid


Setting up a new Grid with RowDefinitions and ColumnDefinitions,

Template: Shortcut: grid
Group: XML
Description: Grid Template
Mime: application/xml
Is expandable template: True
Is surround with template: True

 <Grid>
     <Grid.RowDefinitions>
         <RowDefinition Height="*"/>
         <RowDefinition Height="*"/>
     </Grid.RowDefinitions>
     <Grid.ColumnDefinitions>
         <ColumnDefinition Width="*"/>
         <ColumnDefinition Width="*"/>
     </Grid.ColumnDefinitions>
     $selected$$end$
 </Grid>

$selected$ – is for the code you can select and surround by this snippet.
$end$ – is where the cursor stops after snippet is inserted.

Usage:

ezgif.com-video-to-gif

Template:

1.1. RowDefinitions: grd (Grid Row Definitions Template)

 <Grid.RowDefinitions>
     <RowDefinition Height="Auto"/>
     <RowDefinition Height="Auto"/>
 </Grid.RowDefinitions>

1.2. ColumnDefinitions: gcd (Grid Column Definitions Template)

 <Grid.ColumnDefinitions>
   <ColumnDefinition Width="*"/>
   <ColumnDefinition Width="*"/>
 </Grid.ColumnDefinitions>

Usage:

2. StackLayout


If you want to wrap something inside a StackLayout (or any container for that matter),

Template: Shortcut: stl
Group: XML
Description: StackLayout Template
Mime: application/xml
Is expandable template: True
Is surround with template: True

 <StackLayout>
     $selected$$end$
 </StackLayout>

$selected$ – is for the code you can select and surround by this snippet.
$end$ – is where the cursor stops after snippet is inserted.

Usage:

stl_surround

3. Resource Dictionary and Styles


This is also one of my most used snippet, you can also add converters resources and individual Style templates.

Template:

  <ContentPage.Resources>
     <ResourceDictionary>
         <Style TargetType="$type$">
             <Setter Property="$pName$" Value="$pValue$"/>
         </Style>
     </ResourceDictionary>
 </ContentPage.Resources>

Usage:

rsd

4. Toolbar


Template

 <ContentPage.ToolbarItems>
     <ToolbarItem Name="$name$" Icon="$icon$" Text="$text$" Command="On$name$Tapped" />$end$
 </ContentPage.ToolbarItems>

Usage:

tbi

5. Custom controls


In my previous post, Card View For Xamarin.Forms Using Custom Layouts, I have a custom layout (ShadedCard) that I am using in all my views. I can have a template to set up the card,

Template:

Shortcut: scard
Group: XML
Description: Shaded Card Template
Mime: application/xml

 <controls:ShadedCard Icon="$icon$.png" Title="$title$">
     <controls:ShadedCard.CardContent>
         <!-- Content View -->
     $selected$$end$
     </controls:ShadedCard.CardContent>
     <controls:ShadedCard.ActionView>
         <!-- Action View -->
     </controls:ShadedCard.ActionView>
 </controls:ShadedCard>

$icon$ – Icon property’s default value.
$title$ – Title property’s default value.
$selected$ – is for the code you can select and surround by this snippet.
$end$ – is where the cursor stops after snippet is inserted.

Usage:

Note: These snippets are defined at the IDE level, which means you can use them cross projects. Therefore, be mindful of creating any project specific templates (like the custom control example above.)

Export Templates

To re-use or distribute these templates on other Visual Studio IDE instance or another machine, you can simply get a copy of these snippet files from these locations,

On a Mac,

~Library/VisualStudio/<version>/Snippets

On a Windows running Visual Studio 2017,

...\Visual Studio 2017\Code Snippets\<language>

Download Templates

Here are the snippets shown in this post that you can download for VS 4 Mac,


<?xml version="1.0" encoding="utf-8"?>
<CodeTemplates version="3.0">
<CodeTemplate version="2.0">
<Header>
<_Group>C#</_Group>
<Version />
<MimeType>text/x-csharp</MimeType>
<Shortcut>bctor</Shortcut>
<_Description>Constructor with injections</_Description>
<TemplateType>Unknown</TemplateType>
</Header>
<Variables>
<Variable name="classname">
<Default>notset</Default>
<_ToolTip>Class name</_ToolTip>
<Function>GetCurrentClassName()</Function>
</Variable>
<Variable name="modifier">
<Default>notset</Default>
<Function>GetConstructorModifier()</Function>
</Variable>
</Variables>
<Code><![CDATA[$modifier$$classname$ (INavigationService navigationService) : base(navigationService)
{
$end$
}]]></Code>
</CodeTemplate>
</CodeTemplates>


<?xml version="1.0" encoding="utf-8"?>
<CodeTemplates version="3.0">
<CodeTemplate version="2.0">
<Header>
<_Group>C#</_Group>
<Version />
<MimeType>text/x-csharp</MimeType>
<Shortcut>bprop</Shortcut>
<_Description>Bindable Property Template</_Description>
<TemplateType>Unknown</TemplateType>
</Header>
<Variables>
<Variable name="modifier">
<Default>notset</Default>
<Function>GetClassModifier()</Function>
</Variable>
<Variable name="someproperty">
<Default>SomeProperty</Default>
</Variable>
<Variable name="some">
<Default>Some</Default>
</Variable>
<Variable name="type">
<Default>object</Default>
</Variable>
<Variable name="classname" isEditable="false">
<Default>notset</Default>
<Function>GetCurrentClassName()</Function>
</Variable>
</Variables>
<Code><![CDATA[public static BindableProperty $some$Property = BindableProperty.Create(nameof($some$), typeof($type$), typeof($classname$));
public $type$ $some$
{
get { return ($type$) GetValue($some$Property); }
set { SetValue($some$Property, value); }
}$end$]]></Code>
</CodeTemplate>
</CodeTemplates>


<?xml version="1.0" encoding="utf-8"?>
<CodeTemplates version="3.0">
<CodeTemplate version="2.0">
<Header>
<_Group>C#</_Group>
<Version />
<MimeType>text/x-csharp</MimeType>
<Shortcut>cmdg</Shortcut>
<_Description>Prism DelegateCommand Generic – Creates a generic DelegateCommand property.</_Description>
<TemplateType>Unknown</TemplateType>
</Header>
<Variables>
<Variable name="type">
<Default>string</Default>
</Variable>
<Variable name="commandName">
<Default>CommandName</Default>
</Variable>
</Variables>
<Code><![CDATA[public DelegateCommand<$type$> $commandName$ { get; } = new DelegateCommand<$type$>(On$commandName$Executed);
private void On$commandName$Executed($type$ item)
{
}$end$]]></Code>
</CodeTemplate>
</CodeTemplates>


<?xml version="1.0" encoding="utf-8"?>
<CodeTemplates version="3.0">
<CodeTemplate version="2.0">
<Header>
<_Group>Xml</_Group>
<Version />
<MimeType>application/xml</MimeType>
<Shortcut>gcd</Shortcut>
<_Description>Grid Column Definitions Template</_Description>
<TemplateType>Unknown</TemplateType>
</Header>
<Variables />
<Code><![CDATA[<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>]]></Code>
</CodeTemplate>
</CodeTemplates>


<?xml version="1.0" encoding="utf-8"?>
<CodeTemplates version="3.0">
<CodeTemplate version="2.0">
<Header>
<_Group>Xml</_Group>
<Version />
<MimeType>application/xml</MimeType>
<Shortcut>grd</Shortcut>
<_Description>Grid Row Definitions Template</_Description>
<TemplateType>Unknown</TemplateType>
</Header>
<Variables />
<Code><![CDATA[<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>]]></Code>
</CodeTemplate>
</CodeTemplates>


<?xml version="1.0" encoding="utf-8"?>
<CodeTemplates version="3.0">
<CodeTemplate version="2.0">
<Header>
<_Group>Xml</_Group>
<Version />
<MimeType>application/xml</MimeType>
<Shortcut>grid</Shortcut>
<_Description>Grid Template</_Description>
<TemplateType>Expansion, SurroundsWith</TemplateType>
</Header>
<Variables />
<Code><![CDATA[<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
$selected$$end$
</Grid>]]></Code>
</CodeTemplate>
</CodeTemplates>


<?xml version="1.0" encoding="utf-8"?>
<CodeTemplates version="3.0">
<CodeTemplate version="2.0">
<Header>
<_Group>Xml</_Group>
<Version />
<MimeType>application/xml</MimeType>
<Shortcut>rsd</Shortcut>
<_Description>Resource Dictionary Template</_Description>
<TemplateType>Expansion</TemplateType>
</Header>
<Variables>
<Variable name="type">
<Default>Label</Default>
</Variable>
<Variable name="pName">
<Default>TextColor</Default>
</Variable>
<Variable name="pValue">
<Default>Blue</Default>
</Variable>
</Variables>
<Code><![CDATA[<ContentPage.Resources>
<ResourceDictionary>
<Style TargetType="$type$">
<Setter Property="$pName$" Value="$pValue$"/>
</Style>
</ResourceDictionary>
</ContentPage.Resources>]]></Code>
</CodeTemplate>
</CodeTemplates>


<?xml version="1.0" encoding="utf-8"?>
<CodeTemplates version="3.0">
<CodeTemplate version="2.0">
<Header>
<_Group>Xml</_Group>
<Version />
<MimeType>application/xml</MimeType>
<Shortcut>stl</Shortcut>
<_Description>StackLayout Template</_Description>
<TemplateType>Expansion, SurroundsWith</TemplateType>
</Header>
<Variables />
<Code><![CDATA[<StackLayout>
$selected$$end$
</StackLayout>]]></Code>
</CodeTemplate>
</CodeTemplates>


<?xml version="1.0" encoding="utf-8"?>
<CodeTemplates version="3.0">
<CodeTemplate version="2.0">
<Header>
<_Group>Xml</_Group>
<Version />
<MimeType>application/xml</MimeType>
<Shortcut>tbi</Shortcut>
<_Description>Toolbar Items Template</_Description>
<TemplateType>Expansion</TemplateType>
</Header>
<Variables>
<Variable name="name">
<Default>Item</Default>
</Variable>
<Variable name="icon">
<Default>item.png</Default>
</Variable>
<Variable name="text">
<Default>Hello</Default>
</Variable>
</Variables>
<Code><![CDATA[<ContentPage.ToolbarItems>
<ToolbarItem Name="$name$" Icon="$icon$" Text="$text$" Command="On$name$Tapped" />$end$
</ContentPage.ToolbarItems>]]></Code>
</CodeTemplate>
</CodeTemplates>

Let us know in the comments what is your favorite snippet that you want to add to this list. Enjoy!

Icons by icons8.com

Advertisement

6 thoughts on “Pro Tip: Useful Code Snippets For Your Xamarin.Forms Development

  1. developer9969 says:

    Hi,
    I love xaml snippets .I am using windows and vs 2017 and I found out the following:
    your windows path is wrong for snippets.
    you snippets do not work in windows environment and also the structure does not seem right.

    my snippets have the following header etc…

    <Snippet

    I hope I am missing the obvious.

    • That is correct. These snippets were written on VS 4 Mac and the actual file has a slightly different format, as mentioned in the post. I have updated the path for VS on Windows.

      Thank you for your feedback. I hope these snippets are helpful 🙂

  2. Hi.
    I’m trying to use your snippets codes for xaml in my vs 4 mac. But they not working for me. I write de shortcut in xaml editor but nothing happening, is it necessary active any config in vs 4 mac?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.