我正在Visual Studio 2019中对Visual Studio扩展进行编码,该扩展应从.xml
文件中显示带有代码建议的灯泡。
我当前的问题是,如果当前显示的文本编辑器(.cs
)文件发生更改,则找不到引发该事件的事件。如果有人知道教程或可以告诉我如何以及在何处调用事件以及如何触发事件,我将感到非常高兴。
您可能正在寻找分析仪和代码修复功能的示例。您可以在GitHub上找到lightbulb
示例;当然,它以Visual Studio 2017为目标,但也应该适用于新版本。例如,请参见https://github.com/microsoft/VSSDK-Extensibility-Samples/tree/master/LightBulb
在示例项目中可以看到,您将需要ISuggestedActionsSourceProvider
,ISuggestedActionsSource
和至少一个ISuggestedAction
实现来执行建议的修复。
用ITagger
解决。
internal class TodoTagger : ITagger<TodoTag>
{
private IClassifier m_classifier;
private const string m_searchText = "todo";
internal TodoTagger(IClassifier classifier)
{
m_classifier = classifier;
}
IEnumerable<ITagSpan<TodoTag>> ITagger<TodoTag>.GetTags(NormalizedSnapshotSpanCollection spans)
{
foreach (SnapshotSpan span in spans)
{
//look at each classification span \
foreach (ClassificationSpan classification in m_classifier.GetClassificationSpans(span))
{
//if the classification is a comment
if (classification.ClassificationType.Classification.ToLower().Contains("comment"))
{
//if the word "todo" is in the comment,
//create a new TodoTag TagSpan
int index = classification.Span.GetText().ToLower().IndexOf(m_searchText);
if (index != -1)
{
yield return new TagSpan<TodoTag>(new SnapshotSpan(classification.Span.Start + index, m_searchText.Length), new TodoTag());
}
}
}
}
}
public event EventHandler<SnapshotSpanEventArgs> TagsChanged;
}
[Export(typeof(ITaggerProvider))]
[ContentType("code")]
[TagType(typeof(TodoTag))]
class TodoTaggerProvider : ITaggerProvider
{
[Import]
internal IClassifierAggregatorService AggregatorService;
public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
return new TodoTagger(AggregatorService.GetClassifier(buffer)) as ITagger<T>;
}
}