Accessing Ribbon Controls Programatically in an XM

2020-07-23 03:46发布

问题:

For programming Office Add-ins using C# 4.0, Microsoft provides two different ways of creating and/or modifying the Ribbon interface: you can use the Ribbon Designer or define the Ribbon's layout in Ribbon XML.

If you create a ribbon using the Ribbon designer, the class generated in the code behind has visibility to all the controls you've placed on the ribbon. So if I've placed a RibbonDropDown called "dropdown1", I could use the following code to add an item to it:

RibbonDropDownItem item = Factory.CreateRibbonDropDownItem();
item.Label = submatrix.Name;
item.Tag = submatrix;
this.dropDown1.Items.Add(item);

However, if you create the same Ribbon using Ribbon XML, dropDown1 or Factory aren't found ("The name does not exist in the current context").

Is there a way to access the items added to a Ribbon XML-defined ribbon in code?

回答1:

Might be a little late, but hopefully this helps someone.

I was utterly confused about this same issue. Turns out, you can only access these controls as string ids, and the model is heavy on invalidation events. So for example, when you get a button click via onAction method, you only have the sender's id from the control object, however, in this event handler, you can invalidate the other controls and have their events called using

ribbon.InvalidateControl("MyCtl");

check out this MS Lab, it has everything you need to get up and running