XristosK
XristosK

Reputation: 264

VSTO : how to set a ribbon's button from ThisAddIn class

I have a ribbon, that has button in it. When a user selects new document, I would like to change the ribbon's button's text. I think I've done everything but one line:

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        var wb = this.Application;
        ((Word.ApplicationEvents4_Event)wb).NewDocument += new Word.ApplicationEvents4_NewDocumentEventHandler(Application_NewDocument);

    }
    /// <summary>
    /// When the new button is pressed, the save should be enabled
    /// </summary>
    /// <param name="Doc"></param>
    void Application_NewDocument(Microsoft.Office.Interop.Word.Document Doc)
    {
    // set button's properties here
    }

Upvotes: 2

Views: 4355

Answers (2)

Kiru
Kiru

Reputation: 3565

You need to call the ribbon callback event "getlabel" to set the text. In the Newdocument event set the variable name as shown in the sample code below and then call ribbon InvalidateControl which will repaint your ribbon and executes the callback.

Ribbon.xml

<?xml version="1.0" encoding="UTF-8"?>
<customUI onLoad="Ribbon_Load" xmlns="http://schemas.microsoft.com/office/2006/01/customui">
  <ribbon>
    <tabs>
      <tab idMso="TabAddIns" label="3rd Party Add-ins" />      
          <button id="btnTest" onAction="btnTest_Click" getLabel="get_LabelName" size="large" />        
      </tab>
    </tabs>
  </ribbon>
</customUI>

Ribbon.cs

public class Ribbon : IRibbonExtensibility
{
    private static IRibbonUI ribbon;
    private string buttonText;
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        var wb = this.Application;
        ((Word.ApplicationEvents4_Event)wb).NewDocument += new Word.ApplicationEvents4_NewDocumentEventHandler(Application_NewDocument);

    }
    /// <summary>
    /// When the new button is pressed, the save should be enabled
    /// </summary>
    /// <param name="Doc"></param>
    void Application_NewDocument(Microsoft.Office.Interop.Word.Document Doc)
    {
        buttonText = "New Document Created";
        ribbon.InvalidateControl("btnTest");
    }

     public string get_LabelName(IRibbonControl control)
    {
        return buttonText;
    }
}

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156978

The most easy way is to put the event handler in the Ribbon class. Then you can simply use:

this.Button.Label = "text";

Else, you have to create a property marshaling it to the outside world:

In Ribbon:

public string ButtonText {get {return this.Button.Label;} set {this.Button.Label = value;} }

In ThisAddIn:

Globals.Ribbons.Ribbon.ButtonText = "text";

Upvotes: 4

Related Questions