Home » excel » c# – What's the "proper" way to retrieve a reference to a ribbon object?

c# – What's the "proper" way to retrieve a reference to a ribbon object?

Posted by: admin April 23, 2020 Leave a comment

Questions:

For a VSTO workbook project, is there a best practice for retrieving a reference to the Ribbon object from the ThisWorkbook class?

Here’s what I’m doing: In my Ribbon class, I created a public method called InvalidateControl(string controlID). I need to call that method from the ThisWorkbook class based on when a certain workbook level event fires. But the only way I can see to “get” a reference to that Ribbon object is to do this…

    // This is all in the ThisWorkbook class
    Ribbon ribbon;
    protected override IRibbonExtensibility CreateRibbonExtensibilityObject()
    {
        this.ribbon = new Ribbon();
        return this.ribbon;
    }

…which seems a little smelly. I mean, I have to override CreateRibbonExtensibilityObject() regardless; all I’m doing beyond that is maintaining a local reference to the ribbon so I can call methods against it. But it doesn’t feel right. Is there another, better way to get that reference in the ThisWorkbook class? Or is this pretty acceptable?

Thanks!

How to&Answers:

A much simpler way is to create a global static variable somewhere (e.g. in ThisWorkbook).

public static Ribbon ribbonref;

Then in the code of the Ribbon class, in the event handler for the initialization event (I think the method is called Ribbon1_StartUp() but I’m not sure), set the variable:

private void Ribbon1_StartUp(object sender, EventArg e)
{
    ThisWorkbook.ribbonref = this;
}

(written from memory so may not be exactly right)

You can then use ribbonref to access your ribbon instance.

Answer:

Please see this MSDN page which shows the use of the Globals object:

Globals.Ribbons.MyRibbon.MyObject.Text = "test";