7 Jun 2012

Creating a Custom Web Control for SharePoint 2010


Creating custom web controls in SharePoint 2010.
A custom web control can be created by combining two FeatureMenuTemplate controls with one SubMenuTemplate control as child controls in a new web control. Both of these controls are defined in the Microsoft.SharePoint.WebControls namespace.
Implementing your own custom menu behavior allows you to dynamically modify items in the page load event, such as adding extra information to menu items or processing custom URL tokens for automatic URL rewriting.
A custom web control can be implemented in a nested menu using the following code:
namespace Apress.SP2010.NestedMenu
{
public class CustomAppMenu : WebControl
{
protected SubMenuTemplate customSubMenu;
protected FeatureMenuTemplate customMenuTemplate1;
protected FeatureMenuTemplate customMenuTemplate2;
protected override void CreateChildControls()
{
customSubMenu = new SubMenuTemplate();
customSubMenu.Text = "APress-2010";
customSubMenu.Description = "Custom Menu Actions";
customSubMenu.ImageUrl = "/_layouts/images/lg_ICASCX.gif";
this.Controls.Add(customSubMenu);
customMenuTemplate1 = new FeatureMenuTemplate();
customMenuTemplate1.FeatureScope = "Site";
customMenuTemplate1.Location = "APress.CustomMenu";
customMenuTemplate1.GroupId = "APress";
this.Controls.Add(customMenuTemplate1);
customMenuTemplate2 = new FeatureMenuTemplate();
customMenuTemplate2.FeatureScope = "Site";
customMenuTemplate2.Location = "APress.CustomMenu";
customMenuTemplate2.GroupId = "APress2";
this.Controls.Add(customMenuTemplate2);
}
protected override void OnPreRender(EventArgs e)
{
while (customMenuTemplate1.Controls.Count > 0)
{
MenuItemTemplate menuItem = customMenuTemplate1.Controls[0]
as MenuItemTemplate;
if (menuItem!=null) customSubMenu.Controls.Add(menuItem);
}
// Separator
MenuSeparatorTemplate subMenuSep = new MenuSeparatorTemplate();
customSubMenu.Controls.Add(subMenuSep);
while (customMenuTemplate2.Controls.Count > 0)
{
MenuItemTemplate menuItem = customMenuTemplate2.Controls[0]
as MenuItemTemplate;
if (menuItem != null) customSubMenu.Controls.Add(menuItem);
}
base.OnPreRender(e);
}
}
}

The FeatureMenuTemplate control renders custom actions in a specific menu context, which is defined by the Location and GroupId properties. By using two instances of this control, it's possible to add menu items through custom actions dynamically. The custom action menu item controls of FeatureMenuTemplate, which are automatically initialized in the CreateChildControls method of the FeatureMenuTemplate class, need to be added directly to SubMenuTemplate in the OnPreRender method.

1 comment:

Anonymous said...

Thanks a lot!