Search code examples
visual-studio-extensions

How to run Custom Item Template Wizard from VS Extension command


I have VS Extension with Custom Item Template.
This item uses it's own wizard as I need some information to generate multiple classes.
When I add this item using Add New Item -> [My item] Custom wizard (form) is displayed.
Now I would like to have all my new Item Types available from Context menu on solution Explorer.
I added context menu, but I can not make it show my wizard.
I have tried

dte.ItemOperations.AddNewItem( ... )
dte.LaunchWizard( ... )
ProjectItems.AddFromTemplate( ... ) 

but none of these works.

This is similar problem as in here, but I don't understand solution.


Solution

  • Finally I was able to open Wizard for my custom Item Template. I was passong wrong arguments to LaunchWizard method.
    Parent can be taken for example from selection:

    var parent= dte.SelectedItems.Item(1);
    

    Running wizard:

        internal static async System.Threading.Tasks.Task AddProjectItemFromTemplateAsync(DTE dte, object parent, string templateName, string defaultName)
        {
            ProjectItems items = null;
            string fullPath = null;
            string name = null;
            if (parent is Project project)
            {
                items = project.ProjectItems;
                fullPath = project.Properties.Item("FullPath").Value?.ToString();
                name = project.Name;
            }
            else if(parent is ProjectItem projectItem)
            {
                items = projectItem.ProjectItems;
                fullPath = projectItem.Properties.Item("FullPath").Value?.ToString();
                name = projectItem.Name;
            }
            if (items != null)
            {
                string template = ((Solution2)dte.Solution).GetProjectItemTemplate(templateName, "CSharp");
                object[] parameters = new object[]{
                    EnvDTE.Constants.vsWizardAddItem,
                    name,
                    items,
                    fullPath,
                    defaultName,
                    "",
                    false
                };
                dte.LaunchWizard(template, ref parameters);
            }
        }