Dynamically changing a ribbon label
I've created a VSTO Ribbon for an Outlook 2010 add-in. When I previously used the designer, I was able to dynamically change the label of the ribbon button. I'm now coding this by hand (XML/开发者_开发百科C#) and can't seem to determine how to accomplish the same thing. The "label" item in the XML seems to be static.
FYI - the purpose behind this is to identify the number of items in the gallery for the user.
Thanks.
There is a getLabel attribute you can set on your element. The value is the name of a callback function which is called to provide the label name dynamically. You can programmatically refresh the UI to force all of your callbacks to be called.
This should work for excel and outlook using C#.
I'm going to assume based on your question that you can create the majority of the xml to get the button onto the ribbon, so I'll skip that part. You also didn't mention what kind of an event should change the label button, so I'm going to assume that clicking the button will cause the label text change.
First get the button xml code into place
<button id="YourUniqueId" onAction="YourUniqueId_Click" getLabel="GetYourLabelText">
Create a class level variable that will be accessible to all the methods in your ribbon class before the constructor, and then set the value in your constructor. You'll also need the ribbon UI class variable. This variable should be instantiated when the ribbon loads using a load method in the xml such as onLoad="Ribbon_Load".
public class Ribbon: Office.IRibbonExtensibility
{
private bool _buttonClicked;
private Office.RibbonUI ribbon;
public Ribbon()
{
_buttonClicked = false;
}
public void Ribbon_Load(Office.IRibbonUI ribbonUI)
{
ribbon = ribbonUI;
}
}
Next in your ribbon class you'll need two classes "YourUniqueId_Click" and "GetYourLabelText".
public void YourUniqueId_Click(Office.IRibbonControl Control)
{
//Since the initial value is false and presumably the user just clicked for
//the first (or N-th) time you'll want to set the value to true
if(!_buttonClicked)
{
_buttonClicked = true;
}
//Or if clicking for a second (or N-th + 1) time, set the value to false
else
{
_buttonClicked = false;
}
//Now use the invalidate method from the ribbon variable (from the load method)
//to reset the specific control id (in this case "YourUniqueId") from the xml.
//Invalidating the control will call the method "GetYourLabelText"
ribbon.InvalidateControl(Control.Id);
}
public string GetYourLabelText(Office.IRibbonUI Control)
{
if(_buttonClicked)
{
return "Button is On";
}
else
{
return "Button is Off";
}
}
The "GetYourLabelText" method will run when the ribbon is initially loaded in outlook or excel. Since the class variable "_buttonClicked" is set to false in the constructor, the button label will start off as "Button is Off". Each time the button is clicked the "_buttonClicked" changes boolean state then the button resets calling the "GetYourLabelText" method again.
精彩评论