如何有选择地应用VSTemplate?

Roc*_*cta 2 visual-studio-templates vsix

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

VS项目向导

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

Solution Explorer

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

谢谢!

小智 6

您需要将"可选"模板的文件包含在"根"模板文件夹的子目录中,但是从"根"模板中删除它们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 */
}
Run Code Online (Sandbox Code Playgroud)