Search code examples
outlookvstooutlook-addinoffice-addinsribbonx

How to add a menu item to RibbonMenu


I have placed a RibbonMenu in the VSTO ribbon using the designer. Then I saw that I cannot add items at design time so I am trying to add them programmatically when the ribbon is initialized.

I hav tried with this:

        RibbonMenu control = this.Factory.CreateRibbonMenu();
        control.Label = "Formatear";
        MnuDNI.Items.Add(control);

But an exception is thrown telling that the items collection cannot be modified.

How can I do it?


Solution

  • The Walkthrough: Update the controls on a ribbon at run time shows how to deal with ribbon controls created using a ribbon designer.

    But I'd recommend using ribbon callbacks instead, so you will be aware what is going on and what controls should be displayed. In case of ribbon XML you may consider using the dynamicMenu control which provides the getContent callback which allows providing an XML string that contains the contents of this dynamic menu. For example, a possible declaration of the menu could look like that:

    <menu xmlns="http://schemas.microsoft.com/office/2006/01/customui">
      <button id="dynaButton" label="Button" 
        onAction="OnAction" imageMso="FoxPro"/>
      <toggleButton id="dynaToggleButton" label="Toggle Button" 
        onAction="OnToggleAction" image="logo.bmp"/>
      <menuSeparator id="div2"/>
      <dynamicMenu id="subMenu" label="Sub Menu" getContent="GetSubContent" />
    </menu>
    

    The callback signature should look in the following way:

    C#: string GetContent(IRibbonControl control)
    VBA: Sub GetContent(control As IRibbonControl, ByRef content)
    C++: HRESULT GetContent([in] IRibbonControl *pControl, [out, retval] BSTR *pbstrContent)
    Visual Basic: Function GetContent(control As IRibbonControl) As String
    

    Read more about that in the following series of articles: