visual-studio-extensionsvsixvisual-studio-2022vsixmanifest

VS2022 extensions command initial checked state


I have a VS extensions command based on the default template. It has CommandFlag's TextChanges and TogglePatternAvailable. Depending on a config setting its initial state should be checked, however, this does not appear to be possible.

This is what I want to see on the first load:

Checkbox

I've tried setting Checked to true in the constructor of the command after creating the menu item:

menuItem1 = new OleMenuCommand(ExecuteCommand1, _, BeforeQueryStatus, new CommandID(CommandSet, Command1Id));
menuItem1.Checked = true; // This does not work

I've also tried using the BeforeQueryStatus to change the initial checked state, but it does not seem to be called when opening the Tools menu. Could this be a bug???:

private void BeforeQueryStatus(object sender, EventArgs e)
{
    ThreadHelper.JoinableTaskFactory.Run(async delegate
    {
        await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);
        menuItem1.Checked = true;
    });
}

Clicking the menu item once does trigger BeforeQueryStatus and the state is checked after that, proving that the code does work.

How can I set the initial checked state of the menu item to true depending on a config setting, so in code?


Solution

  • In the end I managed to get it to work by adding the ProvideAutoLoad attribute to my Package. It is unclear if this is the correct way to do this. The pacakge class now looks like this:

    [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
    [Guid(PackageGuidString)]
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [ProvideAutoLoad(VSConstants.UICONTEXT.NoSolution_string, PackageAutoLoadFlags.BackgroundLoad)]
    [ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string, PackageAutoLoadFlags.BackgroundLoad)]
    public sealed class MyPackage : AsyncPackage { ... }