I am associating ribbon to my webpart. I have a need to add more than two webparts in a page.
I do not want to have a separate contextual group/tab for each webpart. Is there a way to check if a specific group/tab exists in the current ribbon on the page?
At this point, when I add more than one webpart to the page, I an getting the following error:
Item has already been added. Key in dictionary: 'Ribbon.MyContextualTabGroup' Key being added: 'Ribbon.MyContextualTabGroup'
Here is my code for your reference:
/// <summary>
/// Gets the web part contextual info.
/// </summary>
public WebPartContextualInfo WebPartContextualInfo
{
get
{
var webPartContextualInfo = new WebPartContextualInfo();
var webPartRibbonContextualGroup = new WebPartRibbonContextualGroup();
var webPartRibbonTab = new WebPartRibbonTab();
webPartRibbonContextualGroup.Id = "Ribbon.MyContextualTabGroup";
webPartRibbonContextualGroup.Command = "MyContextualTab.EnableContextualGroup";
webPartRibbonContextualGroup.VisibilityContext = "MyContextualTab.CustomVisibilityContext";
webPartRibbonTab.Id = "Ribbon.MyTab";
webPartRibbonTab.VisibilityContext = "MyContextualTab.CustomVisibilityContext";
webPartContextualInfo.ContextualGroups.Add(webPartRibbonContextualGroup);
webPartContextualInfo.Tabs.Add(webPartRibbonTab);
webPartContextualInfo.PageComponentId = SPRibbon.GetWebPartPageComponentId(this);
return webPartContextualInfo;
}
}
/// <summary>
/// Adds the contextual tab.
/// </summary>
private void AddContextualTab()
{
SPRibbon spRibbon = SPRibbon.GetCurrent(Page);
if (spRibbon == null) return;
var ribbonExtensions = new XmlDocument();
ribbonExtensions.LoadXml(_contextualTab);
spRibbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ContextualTabs._children");
ribbonExtensions.LoadXml(_contextualTabTemplate);
spRibbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Templates._children");
}
/// <summary>
/// The event handler for the System.Web.UI.Control.PreRender event that occurs immediately before the Web Part is rendered to the Web Part Page it is contained on.
/// </summary>
/// <param name="e">A System.EventArgs that contains the event data.</param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
AddContextualTab();
ClientScriptManager clientScriptManager = Page.ClientScript;
clientScriptManager.RegisterClientScriptBlock(GetType(), "MyWebPart", DelayScript);
}