在自定义Visual Studio编辑器中覆盖字体

gal*_*nus 15 c# visual-studio visual-studio-2012

问题是在VS扩展中使自定义编辑器看起来与当前主题指示不同.编辑器托管在一个对话框中,并且应该具有托管对话框定义的相同字体.

编辑器的内容类型定义如下:

[Export]
[Name("MyContent")]
[BaseDefinition("code")]
public static readonly ContentTypeDefinition ExportContentTypeDefinition = null;
Run Code Online (Sandbox Code Playgroud)

并且有一个分类类型定义:

[Export]
[Name("MyContentText")]
[BaseDefinition("text")]
public static readonly ClassificationTypeDefinition MyTextDefinition = null;
Run Code Online (Sandbox Code Playgroud)

分类器提供程序定义如下:

[Export(typeof(IClassifierProvider))]
[ContentType("MyContent")]
public class ClassifierProvider : IClassifierProvider
{
    [Import]
    public IClassificationTypeRegistryService ClassificationTypesRegistry { get; set; }

    public IClassifier GetClassifier(ITextBuffer textBuffer)
    {
        return new Classifier(
            ClassificationTypesRegistry.GetClassificationType("MyContentText"));
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然分类器只为任何快照提供相同的格式:

public class Classifier : IClassifier
{
    private readonly IClassificationType _classificationType;

    public Classifier(IClassificationType classificationType)
    {
        _classificationType = classificationType;
    }

    public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
    {
        return new [] { new ClassificationSpan(span, _classificationType)};
    }

    public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
}
Run Code Online (Sandbox Code Playgroud)

现在,在代码中,在创建编辑器时,我试图覆盖匹配的属性IClassificationFormatMap:

var contentType = contentTypeRegistryService.GetContentType("MyContent");
var textBuffer = textBufferFactoryService.CreateTextBuffer(initialText, contentType);
var textView = textEditorFactoryService.CreateTextView(textBuffer);

...

var formatMap = classificationFomatMapService
    .GetClassificationFormatMap("MyContentText");

formatMap.DefaultTextProperties = formatMap.DefaultTextProperties
    .SetFontRenderingEmSize(dialog.FontSize)
    .SetTypeface(
        new Typeface(
            dialog.FontFamily,
            dialog.FontStyle,
            dialog.FontWeight,
            dialog.FontStretch));
Run Code Online (Sandbox Code Playgroud)

但是,更改不会影响我的编辑器实例.

此外,从classificationFomatMapService.GetClassificationFormatMap(ITextView)重载返回的格式映射不同于我在上面使用的重载返回的格式映射.更改另一个格式实例也会影响正在运行的Visual Studio实例中的所有代码编辑器,所以我必须得出结论,尽管我付出了努力,但textView以某种方式映射到默认编辑器的分类.

我的问题是:我应该怎么做才能控制为自定义内容类型指定的自定义编辑器的文本外观?

Noa*_*rds 1

我认为您走在正确的道路上,但您需要执行类似于斜体注释扩展的 ViewCreationListener 的操作。具体来说,对视图使用 GetClassificationFormatMap(使用针对您的内容类型键入的视图创建侦听器),而不是设置默认文本属性,而是设置分类类型的属性。正如您所观察到的,格式映射确实在视图之间共享,因此您不想更改默认值。

您可能需要为该类型提供 ClassificationFormatDefinition。也许无论如何都想这样做,只是为了在字体和颜色中显示一些东西。


对于后代:我不认为GetClassificationFormatMap(String)方法采用 ContentType。我手头没有代码了,我根本不记得它是如何工作的,但我不认为“外观类别”与内容类型相关。