特定文件的Visual Studio自定义编辑器

时间:2018-12-29 00:38:51

标签: visual-studio visual-studio-extensions vsix visual-studio-package

上下文:

我正在为Visual Studio 2017创建自定义项目模板,该模板效果很好。在此项目模板内,我发出一个名为“ manifest.json ”的文件。

我需要为“ manifest.json ”文件创建自定义编辑器\设计器,当用户在“ Solution Explorer ”中双击该文件时,它将打开我的自定义编辑器。

我已经在Microsoft Doc上找到了几篇文章(例如Create custom editors and designers),并找到了一些有关创建自定义编辑器和自定义设计器的GitHub示例(例如Editor_With_ToolboxSingleFileGenerator,{{ 3}}和WPFDesigner_XML)。

问题:

  • 大多数文章,示例和文档都说明了如何将自定义编辑器与特定文件扩展名相关联(在我的情况下,我想将编辑器与特定文件中的特定文件“ manifest.json ”相关联)项目)。
  • 与单个文件生成器相关的文章不适合我的解决方案,因为它们谈论的是文件是在设计器中编辑的,而另一个文件是在解决方案中发出的(例如Windows窗体设计器)。

摘要:

我想实现仅针对我的自定义项目模板中的特定文件运行的Visual Studio自定义编辑器\设计器。如何实现呢?

注意:

  • 在定制编辑器中要关联的文件必须命名为“ manifest.json ”。
  • 如果其他项目类型中有一个名为“ manifest.json”的文件,则应执行标准编辑器而不是我的自定义编辑器。

1 个答案:

答案 0 :(得分:1)

Finally after a lot of try and error approach supported with open source samples, I got solution to my problem in the following steps:

  1. Implement custom editor normally as in any of the samples posted in the question (like Editor With Toolbox).
  2. Inside the editor factory class (the class that implements IVsEditorFactory), inside the CreateEditorInstance function, you can make condition like this to limit the editor to JSON files with specific name:
if (System.IO.Path.GetFileName(pszMkDocument).ToLower() != "manifest.json")
{
    return VSConstants.VS_E_UNSUPPORTEDFORMAT;
}
  1. To limit our custom editor to specific custom project we need to mark our target file with metadata (to know more about metadata, look for msbuild metadata) in the template project file (ProjectTemplate.csproj) as the following:
<Content Include="manifest.json" >
    <IsWebExtensionManifest>true</IsWebExtensionManifest>
</Content>
  1. To check for the metadata inside the editor factory, we will continue our work in the CreateEditorInstance function as the following:

    4.1 We already have these 2 parameters passed to the CreateEditorInstance function: (IVsHierarchy pvHier and uint itemid).

    4.2 Use these 2 parameters to obtain IVsBuildPropertyStorage of the parent project (some code examples exist online).

    4.3 Use this code to check for our mark metadata:

buildPropertyStorage.GetItemAttribute(itemid, "IsWebExtensionManifest", out string propVal);
if (!Convert.ToBoolean(propVal))
{
    return VSConstants.VS_E_UNSUPPORTEDFORMAT;
}

Once I finish my custom project with this custom editor, I'll post its GitHub link for more clarity.

相关问题