在运行时导出自定义EditorFormatDefinition

时间:2014-09-16 04:33:38

标签: c# visual-studio visual-studio-extensions vspackage visual-studio-package

在我构建的Visual Studio扩展中,我需要在Visual Studio编辑器中突出显示方法调用。例如:

enter image description here

我想使用HSV颜色根据唯一调用的数量来划分色谱。

如果我将每种颜色导出为自己的EditorFormatDefinition:

,我可以实现突出显示
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = "red-background")]
[Name("red-background")]
[UserVisible(true)]
[Order(After = Priority.High)]
public sealed class RedBackground : ClassificationFormatDefinition
{
    public RedBackground()
    {
        DisplayName = "red-background";
        BackgroundColor = Colors.Red;
    }
}

但是,这需要我手动设置我想提前使用的所有颜色。有没有办法在运行时导出EditorFormatDefinitions

IContentTypeRegistryService和IClassificationTypeRegistryService等某些注册表允许用户在运行时创建新的内容类型和分类。 EditorFormatDefinitions是否存在类似的API。

或者,是否可以在Visual Studio中动态MEF导出EditorFormatDefinition

1 个答案:

答案 0 :(得分:5)

解决方案是使用IClassificationFormatMapService来请求特定的IClassificationFormatMap。然后,我们可以请求TextFormattingRunProperties并创建一组新的文本格式设置属性,我们可以将其添加到IClassificationFormatMap

//No reason to use identifier, just a default starting point that works for me.
var identiferClassificationType = registryService.GetClassificationType("identifier");
var classificationType = registryService.CreateClassificationType(name, SpecializedCollections.SingletonEnumerable(identiferClassificationType));
var classificationFormatMap = ClassificationFormatMapService.GetClassificationFormatMap(category: "text");
var identifierProperties = classificationFormatMap
    .GetExplicitTextProperties(identiferClassificationType);

//Now modify the properties
var color = System.Windows.Media.Colors.Yellow;
var newProperties = identifierProperties.SetForeground(color);
classificationFormatMap.AddExplicitTextProperties(classificationType, newProperties);

//Now you can use or return classificationType...

感谢Kevin Pilch-Bisson对此的帮助。