2

使用Visual Studio扩展性SDK时,我有一个ProjectItem的实例。我试图从这个项目获取文本,所以我可以做一些替代它。我已经看到完成的方式是使用DTE2.ActiveDocument.Selection上的属性。但是,DTE2.ActiveDocument不是我需要的文档,所以我不能使用它。当我尝试访问包含Selection属性的ProjectItem.Document对象时,文档始终为空,并且我得到空引用异常。我也试着不工作以下(即Document是有效的,但Selection属性为null):Visual Studio扩展性 - ProjectInfo.Document始终为空

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); 

总之,我怎么从项目项实例TextSelection实例?

+0

准确使用'Selection'的代码在哪里?发布文档链接。将信息发布到'Selection'属性。 –

+0

@Ramhound用你要求的信息更新了问题。 –

+0

当'selection'设置为'ActiveDocument.Selection'时,当你调试你的代码时,是'null'还是等于'TextSelection'对象?如果这等于'null',那么你已经找到你的问题。代码在哪里选择哪个文档正在使用?它不清楚'_vsApp'是什么类型。 VS2012中不支持'Selection'提供的示例代码。 –

回答

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); 

有没有更好的方法?