从Visual Studio MEF编辑器扩展访问项目系统

Dan*_*ted 4 .net vsx mef visual-studio

我正在使用VS 2010 SDK RC编写Visual Studio编辑器扩展.我希望能够弄清楚当前项目的参考是什么.如何访问与当前编辑器对应的项目?

有关编辑器扩展文档似乎不包含有关如何访问Visual Studio的非编辑器部分的信息.我做了一些搜索,看起来在VS2008中你可以编写可以访问项目系统的加载项,但我正试图从MEF编辑器扩展中获得这个功能.

Cam*_*ers 10

丹尼尔 -

从编辑器到项目是一个多步骤的过程.首先,在编辑器中获取文件的文件名,然后从那里可以找到包含项目.

假设你有一个IWPFTextView,你可以得到这样的文件名:

public static string GetFilePath(Microsoft.VisualStudio.Text.Editor.IWpfTextView wpfTextView)
{
    Microsoft.VisualStudio.Text.ITextDocument document;
    if ((wpfTextView == null) ||
            (!wpfTextView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(Microsoft.VisualStudio.Text.ITextDocument), out document)))
        return String.Empty;

    // If we have no document, just ignore it.
    if ((document == null) || (document.TextBuffer == null))
        return String.Empty;

    return document.FilePath;
}
Run Code Online (Sandbox Code Playgroud)

一旦你有了文件名,就可以得到它的父项目,如下所示:

using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Interop;

public static Project GetContainingProject(string fileName)
{
    if (!String.IsNullOrEmpty(fileName))
    {
        var dte2 = (DTE2)Package.GetGlobalService(typeof(SDTE));
        if (dte2 != null)
        {
            var prjItem = dte2.Solution.FindProjectItem(fileName);
            if (prjItem != null)
                return prjItem.ContainingProject;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

从项目中你可以获得代码模型,我假设参考,但我还没有必要这样做.

希望这可以帮助...

〜卡梅伦