使用 Visual Studio 扩展性 SDK 时,我有一个 ProjectItem
的实例。我正在尝试从该项目中获取文本,以便我可以对其进行一些替换。我看到完成此操作的方法是使用 DTE2.ActiveDocument.Selection
上的属性。然而,DTE2.ActiveDocument
不是我需要的文档,所以我无法使用它。当我尝试访问包含 Selection
的 ProjectItem.Document
对象时属性文档始终为空,并且我收到空引用异常。我还尝试了以下不起作用的方法(即 Document
有效,但 Selection
属性为 null):
Document document = null;
if (!projectItem.IsOpen)
document = projectItem.Open().Document;
我尝试了以下操作,但它没有给我正确的文档,因为我正在处理的 ProjectItem 不是事件文档。有没有办法实现类似于以下代码但使用 ProjectItem.Document
的方法?
TextSelection selection = DTE2.ActiveDocument.Selection;
selection.SelectAll();
string text = selection.Text;
selection.Delete();
//Do replacements
selection.Insert(text);
总而言之,如何从 ProjectItem 实例获取 TextSelection 实例?
最佳答案
像往常一样,在处理 VS SDK 时,答案有点模糊。我解决这个问题的方法(正确或错误)是使 ProjectItem实例化事件文档,然后使用 DTE2.ActiveDocument.Selection
属性来获取文本。这是通过以下方式完成的:
if (!projectItem.IsOpen)
projectItem.Open(@"{7651A701-06E5-11D1-8EBD-00A0C90F26EA}").Document.Activate(); //EnvDTE.Constants.vsViewKindCode
TextSelection selection = _vsApp.ActiveDocument.Selection;
selection.SelectAll();
string text = selection.Text;
selection.Delete();
//Do replacements
text = ReplaceTemplateValues(text, replacements);
selection.Insert(text);
有更好的方法吗?
关于c# - Visual Studio 扩展性 - ProjectInfo.Document 始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13707464/