使用新的边距扩展 Visual Studio 编辑器

文本视图边距放置在边距容器中(请参阅 ContainerMarginPlacement.KnownValues),并在相对于其他边距之前或之后排序(请参阅 MarginPlacement.KnownValues)。

文本视图边距提供程序实现 ITextViewMarginProvider 接口,通过实现 TextViewMarginProviderConfiguration 来配置其提供的边距。在激活时,通过 CreateVisualElementAsync 提供要在边距中托管的 UI 控件。

由于 VisualStudio.Extensibility 中的扩展可能来自 Visual Studio 进程外,因此无法直接将 WPF 用作文本视图边距内容的呈现层。 相反,向文本视图边距提供内容需要创建 RemoteUserControl 以及该控件的相应数据模板。 虽然下面有一些简单的示例,但我们建议在创建文本视图边距 UI 内容时阅读 远程 UI 文档

/// <summary>
/// Configures the margin to be placed to the left of built-in Visual Studio line number margin.
/// </summary>
public TextViewMarginProviderConfiguration TextViewMarginProviderConfiguration => new(marginContainer: ContainerMarginPlacement.KnownValues.BottomRightCorner)
{
    Before = new[] { MarginPlacement.KnownValues.RowMargin },
};

/// <summary>
/// Creates a remotable visual element representing the content of the margin.
/// </summary>
public async Task<IRemoteUserControl> CreateVisualElementAsync(ITextViewSnapshot textView, CancellationToken cancellationToken)
{
    var documentSnapshot = await textView.GetTextDocumentAsync(cancellationToken);
    var dataModel = new WordCountData();
    dataModel.WordCount = CountWords(documentSnapshot);
    this.dataModels[textView.Uri] = dataModel;
    return new MyMarginContent(dataModel);
}

除了配置边距放置之外,文本视图边距提供程序还可以使用 GridCellLengthGridUnitType 属性来配置网格单元格的大小。

文本视图边距通常可视化与文本视图相关的某些数据(例如,当前行号或错误计数),因此大多数文本视图边距提供程序也希望 侦听文本视图事件 以响应文本视图的打开、关闭和用户键入。

Visual Studio 仅创建文本视图边距提供程序的一个实例,而不考虑用户打开的适用文本视图数,因此,如果边距显示一些有状态数据,则提供程序需要保留当前打开的文本视图的状态。

有关详细信息,请参阅 字数计数边距示例

尚不支持需要将内容与文本视图行对齐的纵向文本视图边距。