VSTO – Enabling Ribbon Controls at RunTime

I recently ran into an issue where I needed to enable and disable Ribbon controls in a VSTO plugin where the Ribbon controls were initialized through a Ribbon.xml file.

This can be a bit challenging s the controls in the Ribbon XML file are not available to your code at design time when you are trying to write the actual code.

In addition, I needed to trigger the decision handling logic from another section of code not associated to the Ribbon.

Accomplishing this task involved a number of steps and was done building an integration to Outlook (not sure if this would be similar in Word or Excel).

Identify the controls at run-time

In each control that I wanted to control the state on, at the time of the Ribbon’s instantiation I had them call the “getEnabled” property which called a function that enabled them all and stored an instance of that control in memory for later use.

<labelControl id="lblMyLabel" label="This is My Text" getEnabled="setState" />

In code, I then had a simple List<IRibbonControl> collection created that stored this information.

Note: If you are dynamically adding controls at runtime this could be complex.

Implementing Decision Logic

I won’t go too deep here as every application has their own applicable set of logic but for me a simple eventing framework where I could Fire a State change from any part of my application and subsequently have my ribbon handler listen on the event at start worked perfectly for me.

Changing State

In my aforementioned event, the control determined when to fire a state changed event and thereby would send to the whether the Ribbon should be enabled or disabled.

When receiving the event, it was a simple matter of invalidating the current control on the ribbon and calling the initial state handler that was tied to be ribbon control to reset it’s enabled or disabled status.

foreach (IRibbonControl ctl in _controls)
{
ribbon.InvalidateControl(ctl.Id);
setState(ctl);
}

In doing this, I had 5 controls as part of ribbon – textboxes, labels, buttons and checkboxes and they all worked perfectly.

This was a little more roundabout than I would have liked but I’m happy with the results and consistent implementation.  If I decide to add new controls to my ribbon, all I need to do is ensure the getEnabled property is subscribed to and the state handler will take care of the rest.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s