繼續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的配置資訊要根據具體的強命名資訊作適當更改。