【问题标题】:Visual Studio Extensibility - ProjectInfo.Document is always nullVisual Studio 可扩展性 - ProjectInfo.Document 始终为空
【发布时间】:2012-12-04 16:32:56
【问题描述】:

使用 Visual Studio 可扩展性 SDK 时,我有一个 ProjectItem 的实例。我正在尝试从该项目中获取文本,以便可以对其进行一些替换。我看到的方法是使用DTE2.ActiveDocument.Selection 上的属性。但是,DTE2.ActiveDocument 不是我需要的文档,所以我不能使用它。当我尝试访问包含 Selection 属性的 ProjectItem.Document 对象时,文档始终为空,并且出现空引用异常。我还尝试了以下不起作用的方法(即Document 有效,但Selection 属性为空):

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 实例?

【问题讨论】:

  • 使用Selection的代码到底在哪里?发布指向文档的链接。在Selection 属性上发布信息。
  • @Ramhound 用您要求的信息更新了问题。
  • 调试代码时,selection 设置为等于ActiveDocument.Selection 之后是null 还是等于TextSelection 对象?如果它等于null,那么你已经找到了你的问题。您选择使用哪个文档的代码在哪里?目前尚不清楚_vsApp 到底是什么类型。 VS2012 不支持为Selection 提供的示例代码。
  • @Ramhound 问题是 ActiveDocument 不是我要调整的文档。我已经有一个 ProjectItem,我想从中获取文本。
  • @Ramhound 另外,最后一句话一直都有,我认为它很好地总结了我的终极问题(如何从 ProjectItem 实例中获取 TextSelection 实例)。

标签: c# visual-studio-2012 visual-studio-extensions visual-studio-sdk


【解决方案1】:

像往常一样处理 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);

有没有更好的办法?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 2011-07-27
    相关资源
    最近更新 更多