Visual Studio自定义模板(三)

继续Visual Studio自定义模板(二),要想实现动态的自定义模板参数,还要回到vstemplate文件,在该文件中,我们可以配置自己的向导扩展WizardExtension, 通过WizardExtension,我们就可以在向导生成文件的过程中加入自定义的代码了。

首先我们实现一个简单的自定义Wizard,

  
    namespace MyTemplate
{
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TemplateWizard;

public class MyWizard : IWizard
{
/// <summary>
/// Runs custom wizard logic before opening an item in the template.
/// </summary>
/// <param name="projectItem">The project item that will be opened.</param>
public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
{
}

/// <summary>
/// Runs custom wizard logic when a project has finished generating.
/// </summary>
/// <param name="project">The project that finished generating.</param>
public void ProjectFinishedGenerating(EnvDTE.Project project)
{
}

/// <summary>
/// Runs custom wizard logic when a project item has finished generating.
/// </summary>
/// <param name="projectItem">The project item that finished generating.</param>
public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
{
}

/// <summary>
/// Runs custom wizard logic when the wizard has completed all tasks.
/// </summary>
public void RunFinished()
{
}

/// <summary>
/// Runs the started.
/// </summary>
/// <param name="automationObject">The automation object.</param>
/// <param name="replacementsDictionary">The replacements dictionary.</param>
/// <param name="runKind">Kind of the run.</param>
/// <param name="customParameters">The custom parameters.</param>
public void RunStarted(object automationObject,
Dictionary
<string, string> replacementsDictionary,
WizardRunKind runKind,
object[] customParameters)
{
replacementsDictionary.Add(
"$MyDate$", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}

/// <summary>
/// Indicates whether the specified project item should be added to the project.
/// </summary>
/// <param name="filePath">The path to the project item.</param>
/// <returns>
/// true if the project item should be added to the project; otherwise, false.
/// </returns>
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
}
}

至于IWizard各个方法的具体定义,请大家参考MSDN,这里,我在RunStarted方法中添加了一个自模板参数$MyDate$,它的值为DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),也就是说在模板文件中所有$MyDate$都会被替换成指定的具体的日期字符串。

下一步就是在vstemplate文件中加入我们定义的Wizard的配置,VS有一个要求,所有向导扩展都必须安装在GAC中,所以我们要强命名我们刚才生成的程序集,安装到GAC中。首先在[我的文档]\Visual Studio 2005\Templates\ItemTemplates中找到我们在2中生成的模板,解压后修改vstemplate文件如下,

< VSTemplate Version ="2.0.0" xmlns ="http://schemas.microsoft.com/developer/vstemplate/2005" Type ="Item" >

< WizardExtension >
< Assembly > MyTemplate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5ea13aa0d9868d4b </ Assembly >
< FullClassName >
MyTemplate.MyWizard
</ FullClassName >
</ WizardExtension >
</ VSTemplate >
 
  

注,上面Assembly的配置信息要根据具体的强命名信息作适当更改。

你可能感兴趣的:(自定义)