在扩展中写 Visual Studio 设置不留

Writing Visual Studio settings in an extension do not stay

在我为 Visual Studio 2015 编写的扩展程序中,我想更改制表符大小和缩进大小,因为在工作中我们有不同的设置,因为我正在为开源项目开发(公司历史可以追溯到我们的C期)。 我在我的命令 class:

中写了下面的代码
private const string CollectionPath = @"Text Editor\CSharp";
private void MenuItemCallback(object sender, EventArgs e)
{
  var settingsManager = new ShellSettingsManager(ServiceProvider);
  var settingsStore = settingsManager.GetWritableSettingsStore(SettingsScope.UserSettings);
  var tabSize = settingsStore.GetInt32(CollectionPath, "Tab Size", -1);
  var indentSize = settingsStore.GetInt32(CollectionPath, "Indent Size", -1);
  if (tabSize != -1 && indentSize != -1)
  {
    settingsStore.SetInt32(CollectionPath, "Tab Size", 2);
    settingsStore.SetInt32(CollectionPath, "Indent Size", 2);
  }
}

在实验性配置单元中进行测试时,它会在您逐步执行该方法时更改它,但当您打开“选项”对话框时,它会保持原始值。 当您再次调试时,值保持原始状态。

我忘记了什么或做错了什么?

通过 EnvDTE 程序集中的 Properties 功能直接访问 Visual Studio 选项。

private void ChangeTabs(DTE vs, int newTabSize, int newIndentSize)
{
    var cSharp = vs.Properties["TextEditor", "CSharp"];

    EnvDTE.Property lTabSize = cSharp.Item("TabSize");
    EnvDTE.Property lIndentSize = cSharp.Item("IndentSize");

    lTabSize.Value = newTabSize;
    lIndentSize.Value = newIndentSize;
}

private void ChangeSettings()
{
   DTE vs = (DTE)GetService(typeof(DTE)); 
   ChangeTabs(vs, 3, 3);
}

供参考:Controlling Options Settings

待完成。这是正确答案:

在构造函数中你需要添加

_dte2 = (DTE2) ServiceProvider.GetService(typeof (DTE));

而命令是这样的

    _dte2.Properties["TextEditor", "CSharp"].Item("TabSize").Value = 2;
    _dte2.Properties["TextEditor", "CSharp"].Item("IndentSize").Value = 2;
    _dte2.Commands.Raise(VSConstants.CMDSETID.StandardCommandSet2K_string, (int)VSConstants.VSStd2KCmdID.FORMATDOCUMENT, null, null);

当您重新启动 Visual Studio 时,更改的选项会被默认值覆盖,这是一个问题。