Skip to main content

...

....

C# - Visual Studio- How To Create Item Templates [Beginner]


Visual Studio actually has a very powerful wizard and template system, which when used correctly, can automate large amounts of tedious work. Today we are going to take a look at how to create Item Templates for Visual Studio, which is actually extremely simple to do.

We are going to walk through creating an Item Template for a "Switch On The Code" version of UserControl. Often times, I don't like the normal new UserControl template, especially if I won't be using the form designer at all with the new control. So we are going to be making our own. It will be pretty simple, but it will show off the basics of item templates, and hopefully give you enough information to start making your own templates!

First off, you probably care about how you use custom templates in the first place. They are in a very obvious spot, but if you've never used them, you may never have noticed. So you want to add an item to a project - first you'll probably go through the context menu on the project and choose "Add Item", like so:

VS Add Item Context
Menu

Once you click that menu item, you will see a dialog that looks like this:

VS Add Item
Dialog

For each category on the left, the section on the right will have two sections: "Visual Studio installed templates" and "My Templates". Any templates that you make will show up under "My Templates" - as you can see in the image above, in this particular case "SOTC User Control" shows up in that section under the category "Windows Forms". And using the template is as simple as choosing that item and clicking "Add."

So that is how to use a template - now on to making your own. A template is generally made up of 3 or more items - an icon, a 'vstemplate' file (which holds all the meta information about the template), and 1 or more code template files. First we are going to take a look at the 'vstemplate' file:
<VSTemplate Type="Item" Version="2.0.0" 
    xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name>SOTC User Control</Name>
    <Description>SOTC User Control Template</Description>
    <DefaultName>MyUserControl</DefaultName>
    <ProjectType>CSharp</ProjectType>
    <Icon>SOTCIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <ProjectItem TargetFileName="$fileinputname$.cs" ReplaceParameters="true">
      SOTCUserControl.cs
    </ProjectItem>
  </TemplateContent>
</VSTemplate>
 
Here we have the 'SOTCUserControl.vstemplate' file. Let's walk through the important chunks. At the top, we have the root VSTemplate element, with a few attributes. The Type is the only one you will probably want to change - it can be "Item" or "Project", depending on if this is an item or a project template. Next is the TemplateData section. Here are things like the name of the template, its description and so forth. DefaultName is the default name for a new item using this template, and ProjectType specifies what type of project this template can be used for (CSharp, VisualBasic, or Web). The final item here is the Icon, which is just the name of the icon file to be used with the template in the "Add New Item" dialog.

All of those elements are required children of the TemplateData element (except for DefaultName). There are a number of other possible elements - and if you feel adventurous you can check them all out here.

Now we are on to the TemplateContent element. This is where you list all the items that will get added to the project on the instantiation of this template. In this case, there is only one item. Here is where you actually start to see templating come into play. The TargetFileName attribute represents the final file name that will be used for this item. In this case we are using the string "\$fileinputname\$.cs". However, this is not an ordinary string - $fileinputname$ is a template parameter. When the template is instantiated, $fileinputname$ will be replace by a file-name safe version of the name typed into the "Name" text box on the Add New Item dialog. You will see a bunch more of those template parameters in a few moments.

The ReplaceParameters attribute tells Visual Studio if it should parse the project item for template parameters to replace. In this case we want it to, so we have it set to true. And the actual content on the ProjectItem element is the name of the raw template file - in this case "SOTCUserControl.cs".
So lets take a look at the contents of "SOTCUserControl.cs":
using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace $rootnamespace$
{
  public class $safeitemname$ : UserControl
  {
    public $safeitemname$()
    {
      DoubleBuffered = true;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
      base.OnPaint(e);
    }

    protected override void OnResize(EventArgs e)
    {
      base.OnResize(e);
    }

    /// <summary> 
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources 
    /// should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
      if (disposing)
      {
        //Dispose managed resources here  
      }

      base.Dispose(disposing);
    }    
  }
}
 
Nothing really crazy here, it looks like C#, except for the scattered template parameters. And when the template is instantiated, those parameters will be replaced with the correct information. You can check out a list of all the possible template parameters here.

So lets say I added an item using this template, and gave it the name "YaySOTC" (and I added it inside of a project with the namespace "MyBestProject"). You would end up with file that looked like this:
using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace MyBestProject
{
  public class YaySOTC : UserControl
  {
    public YaySOTC()
    {
      DoubleBuffered = true;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
      base.OnPaint(e);
    }

    protected override void OnResize(EventArgs e)
    {
      base.OnResize(e);
    }

    /// <summary> 
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources 
    /// should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
      if (disposing)
      {
        //Dispose managed resources here  
      }

      base.Dispose(disposing);
    }    
  }
}
 
There is still one small part you might be wondering about. Now that you have this vstemplate file, and some templated code, where are you supposed to put them? A very good question. First off, you want to zip up all the files that make up you template (you can name the zip file whatever you want). So in this particular case, we would have a zip file containing:
SOTCUserControl.vstemplate
SOTCUserControl.cs
SOTCIcon.ico
 
Then, you want to take this zip file and put it in the appropriate user templates directory. The root template directory is usually at "Visual Studio 2008\Templates\" inside of your "My Documents" folder. For this particular template, we want to put it inside of "Visual Studio 2008\Templates\ItemTemplates\Visual C#\" - to specify that this is an item template, and that is for C#. This will get your template to appear in the "Add New Item" dialog. However, if you want the template to appear under a specific category, you need to make a folder for that category. For example, we want the SOTC User Control to appear under the "Windows Forms" category, so we need to make the directory "Windows Forms". So the final path for the zip file will be: "Visual Studio 2008\Templates\ItemTemplates\Visual C#\Windows Forms\".

Well, that is is for a simple introduction to using item templates. You can download the template we made today here if you would like to play around with it. If you want to learn more about template for Visual Studio, there is a whole bunch of information onMSDN.

Source Files:

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV