I'm trying to get the active C# Editor IWpfTextView in VS2019 extension. I'm using a small MEF service to inject a view into the VSAsyncPackage. But it is not very reliable - sometimes the injected view is wrong (e.g. from another view) or missing. Here is the service:
public interface IActiveViewAccessor
{
IWpfTextView? ActiveView { get; }
}
[Export(typeof(IWpfTextViewConnectionListener))]
[Export(typeof(IActiveViewAccessor))]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Document)]
internal sealed class ActiveViewConnectionListener : IWpfTextViewConnectionListener, IActiveViewAccessor
{
public IWpfTextView? ActiveView { get; private set; }
public void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
this.ActiveView = textView;
}
public void SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
this.ActiveView = null;
}
}
This service is being injected into the VSPackage as:
this.viewAccessor = this.exportProvider.GetExportedValue<IActiveViewAccessor>();
and it is being used as:
var view = this.viewAccessor?.ActiveView;
Is there a better and more stable way to get IWpfTextView in the async VSPackage?
So far, here are some related questions but not exactly what I'd expected: