演练:将内容类型链接到文件扩展名

可以使用编辑器托管扩展性框架(MEF)扩展定义自己的内容类型并将文件扩展名链接到它。 在某些情况下,文件扩展名已由语言服务定义。 但是,若要将其与 MEF 一起使用,仍必须将它链接到内容类型。

创建 MEF 项目

  1. 创建 C# VSIX 项目。 (在 “新建项目 ”对话框,选择 Visual C# /扩展性,然后选择 VSIX Project。)将解决方案 ContentTypeTest命名为 。

  2. 在 source.extension.vsixmanifest 文件中,转到“资产”选项卡,并将“类型”字段设置为 Microsoft.VisualStudio.MefComponent,将字段设置为当前解决方案中的 A 项目,将“项目”字段设置为项目的名称。

定义内容类型

  1. 添加一个类文件并将其命名为 FileAndContentTypes

  2. 添加对下列程序集的引用:

    1. System.ComponentModel.Composition

    2. Microsoft.VisualStudio.Text.Logic

    3. Microsoft.VisualStudio.CoreUtility

  3. 添加以下 using 指令。

    using System.ComponentModel.Composition;
    using Microsoft.VisualStudio.Text.Classification;
    using Microsoft.VisualStudio.Utilities;
    
    
  4. 声明包含定义的静态类。

    internal static class FileAndContentTypeDefinitions
    {. . .}
    
  5. 在此类中,导出 ContentTypeDefinition 名为“hid”,并将其基本定义声明为“text”。

    internal static class FileAndContentTypeDefinitions
    {
        [Export]
        [Name("hid")]
        [BaseDefinition("text")]
        internal static ContentTypeDefinition hidingContentTypeDefinition;
    }
    
  • 若要将此内容类型映射到文件扩展名,请导出 FileExtensionToContentTypeDefinition 扩展名 为 .hid 和内容类型“hid”的扩展名。

    internal static class FileAndContentTypeDefinitions
    {
         [Export]
         [Name("hid")]
         [BaseDefinition("text")]
        internal static ContentTypeDefinition hidingContentTypeDefinition;
    
         [Export]
         [FileExtension(".hid")]
         [ContentType("hid")]
        internal static FileExtensionToContentTypeDefinition hiddenFileExtensionDefinition;
    }
    

将内容类型添加到编辑器导出

  1. 创建编辑器扩展。 例如,可以使用演练中所述 的边距字形扩展:创建边距字形

  2. 添加在此过程中定义的类。

  3. 导出扩展类时,请向其添加 ContentTypeAttribute 类型为“hid”。

    [Export]
    [ContentType("hid")]