如何使用复选框创建命令菜单项?

时间:2014-04-12 17:04:10

标签: visual-studio visual-studio-extensions vsix vspackage vsct

我正在编写VSPackage,我需要有复选框的菜单项,就像下面的示例图片一样:

enter image description here

我查看了关于 .vsct 文件的this msdn reference,对于解释如何操作的任何信息,芽都没有。我现在拥有的是带有图标和文本的标准菜单项(来自MyPackage.vsct文件的代码示例):

<Buttons>     
  <Button guid="guidMyPackageCmdSet" id="cmdidMyPackage" type="Button">
    <Icon guid="guidImages" id="myPackageBitmap" />
    <CommandFlag>TextChanges</CommandFlag>
    <CommandFlag>DontCache</CommandFlag>
    <CommandFlag>FixMenuController</CommandFlag>
    <Strings>
      <ButtonText>MyPackage</ButtonText>
    </Strings>
  </Button>      
</Buttons>

我需要这个额外的复选框。怎么做?

1 个答案:

答案 0 :(得分:3)

CheckedVisibleEnabledSupported等属性无法通过VSCT文件定义。您需要一个控制命令状态的命令处理程序。我创建了一个基类,它包装OleMenuCommand实例的创建并处理命令的BeforeQueryStatus事件。这是我的实现的精简版本,但它会让你知道如何解决它...

internal abstract class CommandHandler : IDisposable
{
    private readonly OleMenuCommand command;

    protected CommandHandler(Guid group, int id)
    {
        var commandid = CommandID(group, id);
        this.command = new OleMenuCommand(this.Invoke, commandId);
        this.command.BeforeQueryStatus += this.OnBeforeQueryStatus;
    }

    protected virtual void OnExecute() { } 

    protected virtual void OnQueryStatus(QueryStatusEventArgs e) { }

    private void Invoke(object sender, EventArgs e)
    {
        this.OnExecute();
    }

    private void OnBeforeQueryStatus(object sender, EventArgs e)
    {
        OleMenuCommand command;
        if ((command = sender as OleMenuCommand) != null)
        {
            var e = new QueryCommandEventArgs
            {
                Checked = command.Checked,
            }

            this.OnQueryStatus(e);

            command.Checked = e.Checked;
        }
    }

    public void Dispose()
    {
        this.command.BeforeQueryStatus -= this.OnBeforeQueryStatus;
    }
}

public class QueryCommandEventArgs : EventArgs
{
    public bool Checked { get; set; }
}

CommandHandler类允许控制任何菜单命令的状态。只需从中派生新的处理程序实现并覆盖OnExecuteOnQueryStatus方法,例如......

internal sealed class MyCommand : CommandHandler
{
    private bool checked;

    public MyCommand() : base(GuidCmdSet, MyCommandId) { }

    protected override void OnExecute()
    {
        this.checked = !this.checked; // toggle checked state
    }

    protected override void OnQueryStatus(QueryStatusEventArgs e)
    {
        e.Checked = this.checked;
    }
}