如何有选择地应用VSTemplate?

时间:2013-09-06 18:09:42

标签: vsix visual-studio-templates

我正在为我的公司创建一个用于MVC 4应用程序的自定义VSTemplate,它使用的向导与创建新MVC4应用程序时出现的向导相当。当开发人员创建此类型的新应用程序时,我想要应用两个模板中的一个:

VS Project Wizard

这两个条目都对应于我的VSIX项目中名为ProjectTemplates的文件夹中定义的模板:

Solution Explorer

我的问题是,当向导运行时如何应用正确的模板?我知道如何使用多个项目创建一个vstemplate(使用vstemplate中的ProjectCollection节点),但这不是我想要做的,因为它们永远不会一起部署。我看到我可以将vstemplates作为Assets添加到我的vsixmanifest文件中,但我不确定如何有条件地仅应用一个模板。

谢谢!

1 个答案:

答案 0 :(得分:6)

您需要将“可选”模板的文件包含在“root”模板文件夹的子目录中,但 EXCLUDE 来自TemplateContent Element的“根”模板。

您的IWizard实施需要保留对EnvDTE.DTE对象(RunStarted的第一个参数)的引用,并在ProjectFinishedGenerating中使用它来将项目添加到解决方案使用与用户选择的模板匹配的模板。

public class SelectTemplatesWizard : IWizard
{
    private EnvDTE.DTE _dte = null;

    private string _solutionDir = null;

    private string _templateDir = null;

    public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
    {
        // Store the reference to the environment for later use
        _dte = automationObject as EnvDTE.DTE;

        /*
          The value of the item in the replacements dictionary for the key 
          $destinationdirectory$ is populated with the physical location of
          the directory (named based on the user entered project name) created
          sibling to the solution file.

          The solution directory will be this directories parent 
          when the Type attribute of the VSTemplate element is ProjectGroup
        */
        _solutionDir = System.IO.Path.GetDirectoryName(replacementsDictionary["$destinationdirectory$"]);

        // customParams[0] is a default custom param that contains the physical location of the template that is currently being applied
        _templateDir = System.IO.Path.GetDirectoryName(customParams[0] as string);
    }

    public void ProjectFinishedGenerating(Project project)
    {
        int userSelected = 1;
        string name= null, projectPath= null, templatePath = null;

        switch (userSelected)
        {
            case 0:
                {
                    name = "Angular";
                    projectPath = System.IO.Path.Combine(_solutionDir, "Angular");
                    templatePath = System.IO.Path.Combine(_templateDir , "Angular\Angular.vstemplate");
                }
                break;
            case 1:
                {
                    name = "MVC4";
                    projectPath = System.IO.Path.Combine(_solutionDir, "MVC4");
                    templatePath = System.IO.Path.Combine(_templateDir , "MVC4\MVC4.vstemplate");
                }
                break;
        }
        _dte.Solution.AddFromTemplate(templatePath, projectPath, name);
    }

    /* Other IWizard methods excluded for brevity */
}