共用方式為


變更功能表命令的文字

下列步驟說明如何使用 IMenuCommandService 服務來變更功能表命令的文字標籤。

使用 IMenuCommandService 變更功能表命令標籤

  1. 使用名為 ChangeMenuText 的功能表命令建立名為 MenuText 的 VSIX 專案。 如需詳細資訊,請參閱使用功能表命令建立延伸模組

  2. 在 .vsct 檔案中,將 TextChanges 旗標新增至功能表命令,如下列範例所示。

    <Button guid="guidChangeMenuTextPackageCmdSet" id="ChangeMenuTextId" priority="0x0100" type="Button">
        <Parent guid="guidChangeMenuTextPackageCmdSet" id="MyMenuGroup" />
        <Icon guid="guidImages" id="bmpPic1" />
        <CommandFlag>TextChanges</CommandFlag>
        <Strings>
            <ButtonText>Invoke ChangeMenuText</ButtonText>
        </Strings>
    </Button>
    
  3. 在 ChangeMenuText.cs 檔案中,建立將在功能表命令顯示之前呼叫的事件處理常式。

    private void OnBeforeQueryStatus(object sender, EventArgs e)
    {
        var myCommand = sender as OleMenuCommand;
        if (null != myCommand)
        {
            myCommand.Text = "New Text";
        }
    }
    

    您也可以變更 OleMenuCommand 物件上的 VisibleCheckedEnabled 屬性,在此方法中更新功能表命令的狀態。

  4. 在 ChangeMenuText 建構函式中,以建立代表功能表命令的 OleMenuCommand (而不是 MenuCommand),新增 BeforeQueryStatus 事件處理常式,並將功能表命令提供給功能表命令服務的程式碼取代原始的命令初始化和放置程式碼。

    它看起來應該像這樣:

    private ChangeMenuText(AsyncPackage package, OleMenuCommandService commandService)
    {
        this.package = package ?? throw new ArgumentNullException(nameof(package));
        commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));
    
        var menuCommandID = new CommandID(CommandSet, CommandId);
        var menuItem = new OleMenuCommand(this.Execute, menuCommandID);
        menuItem.BeforeQueryStatus += new EventHandler(OnBeforeQueryStatus);
        commandService.AddCommand(menuItem);
    }
    
  5. 建置此專案並開始偵錯。 隨即出現 Visual Studio 實驗執行個體。

  6. 在 [工具] 功能表上,您應該會看到名為 [叫用 ChangeMenuText] 的命令。

  7. 按一下該命令。 您應該會看到宣佈已呼叫 MenuItemCallback 的訊息方塊。 當您關閉該訊息方塊時,應該會看到 [工具] 功能表上的命令名稱現在是 [新增文字]