Search code examples
c#.netexcelcomexcel-dna

How to retrieve controls from ribbon ExcelDNA


I was wondering how you are able to retrieve controls from the custom RibbonUI defined in the .dna file that ExcelDNA generates? Currently I am implementing a login workflow one of the buttons is disabled. Where the user would login and if successful would enable the disabled button.


Solution

  • The Office ribbon interface is purely based on callbacks. So you can't actually 'retrieve controls' from the ribbon and set properties on these. You implement state changes by triggering a callback - in this case probably to your getEnabled callback. To trigger the invalidation of the ribbon, so that your callbacks will be evaluated again, you call Invalidate on the ribbon interface that you get when the ribbon is loaded.

    Some C# code that implements this might look like this:

    public class MyRibbon: ExcelRibbon 
    { 
      private static IRibbonUI _ribbonUi; 
    
      // This ribbon xml can be returned in code, or places in the .dna     file 
      public override string GetCustomUI(string uiName) 
      { 
        return 
        @" 
        <customUI onLoad='Ribbon_Load' 
                  xmlns='http://schemas.microsoft.com/office/2006/01/customui'> 
          <ribbon> 
            <tabs> 
              <tab idMso='TabAddIns'> 
                <group id='group1' label='Group1'> 
                  <button id='button1' getEnabled='btn_GetEnabled' getLabel='btn_GetLabel' /> 
                </group> 
              </tab> 
            </tabs> 
          </ribbon> 
        </customUI> 
        "; 
      } 
      public void Ribbon_Load(IRibbonUI sender) 
      { 
        _ribbonUi = sender; 
      } 
      public bool btn_GetEnabled(IRibbonControl control) 
      { 
        return true; 
      } 
      public bool btn_GetLabel(IRibbonControl control) 
      { 
        return "My Button"; 
      } 
      public static void Refresh() 
      { 
        if (_ribbonUi != null) { _ribbonUi.Invalidate(); } 
      } 
    }