我是VS扩展开发的新手.我目前正在使用VS 2015中的文本装饰样本,并且能够正确显示彩色框.现在我想扩展示例,以便装饰只出现在某些文件名上.
谷歌说我可以使用ITextDocumentFactoryService.TryGetTextDocument与IWpfTextView.TextBuffer属性的接口来获取文件名.听起来不错.但我似乎无法真正获得界面.
在我的班上,我有:
[Import]
public ITextDocumentFactoryService TextDocumentFactoryService = null;
Run Code Online (Sandbox Code Playgroud)
但它始终是NULL.
我该怎么ITextDocumentFactoryService办?
namespace Test
{
internal sealed class TestAdornment
{
[Import]
public ITextDocumentFactoryService TextDocumentFactoryService = null;
public TestAdornment(IWpfTextView view)
{
}
/// <summary>
/// Adds the scarlet box behind the 'a' characters within the given line
/// </summary>
/// <param name="line">Line to add the adornments</param>
private void CreateVisuals(ITextViewLine line)
{
// TextDocumentFactoryService is NULL
}
}
}
Run Code Online (Sandbox Code Playgroud)
TextAdornmentTextViewCreationListener.cs
[Export(typeof(IWpfTextViewCreationListener))]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Document)]
internal sealed class TextAdornmentTextViewCreationListener : IWpfTextViewCreationListener
{
[Import]
public ITextDocumentFactoryService textDocumentFactory { get; set; }
//...
public void TextViewCreated(IWpfTextView textView)
{
new TextAdornment(textView, textDocumentFactory);
}
}
Run Code Online (Sandbox Code Playgroud)
文字装饰.cs
internal sealed class TextAdornment
{
private readonly ITextDocumentFactoryService textDocumentFactory;
private ITextDocument TextDocument;
//...
public TextAdornment(IWpfTextView view, ITextDocumentFactoryService textDocumentFactory)
{
//...
this.textDocumentFactory = textDocumentFactory;
//...
}
internal void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
var res = this.textDocumentFactory.TryGetTextDocument(this.view.TextBuffer, out this.TextDocument);
if (res)
{
//this.TextDocument.FilePath;
}
else
{
//ERROR
}
}
}
Run Code Online (Sandbox Code Playgroud)
您通过依赖注入获得了它。
由于您只提交了 2 行代码,我认为您的上下文已设置,要么由您显式设置,要么由调用您代码的某些环境隐式设置。
然后老大哥会在你第一次访问它之前自动为你设置它。
...或者...
您可以使用构造函数注入来代替。注意:创建类的人不是您。
private readonly ITextDocumentFactoryService _textDocumentFactoryService;
[ImportingConstructor]
internal YourClass(ITextDocumentFactoryService textDocumentFactoryService)
{
_textDocumentFactoryService = textDocumentFactoryService;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
623 次 |
| 最近记录: |