Wednesday, March 3, 2010

SharePoint TreeView Site Navigation

This is a really simple and powerful solution for site navigation within a site collection. It consists of a TreeView control, a PortalSiteMapProvider and a SiteMapDataSource. It sounds like there's a lot going on and there is, but SharePoint is taking care of most of the work for us.


The TreeView control gives a familiar look most users will quickly recognize. It can be easily styled  with css or skins.




Here is the editor of the webpart. The TreeView section has been added for a few customizations. The Site Map Provider is provided by SharePoint. Additional providers can be found in the web.config file. Number of levels to Show sets the number of levels to expand. Only Display Subsites if checked will only display the current site and it's subsites.

The code below creates and customizes the sitemapprovider.
        //setup the sitemapprovider
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            SiteMapProvider siteMapProvider = SiteMap.Providers[_siteMapProvider];
            if (siteMapProvider == null)
            { return; }

            InitPortalSiteMapProvider(siteMapProvider);
        }

        //set some defaults for the customized data provider
        //this is intended to only show sites and not pages
        private void InitPortalSiteMapProvider(SiteMapProvider siteMapProvider)
        {
            if (siteMapProvider is PortalSiteMapProvider)
            {
                _provider = siteMapProvider as PortalSiteMapProvider;
                _provider.DynamicChildLimit = 0;
                _provider.EncodeOutput = true;
                _provider.IncludePages = PortalSiteMapProvider.IncludeOption.Never;
                _provider.IncludeSubSites = PortalSiteMapProvider.IncludeOption.Always;
                _provider.IncludeHeadings = false;
                _provider.IncludeAuthoredLinks = false;
            }
        }

Here's the CreateChildControls method where everything is put together.
        protected override void CreateChildControls()
        {
            Controls.Clear();
            //create the datasource
            _datasource = new SiteMapDataSource();
            //associate the datasource with the customized provider
            _datasource.Provider = _provider;
            //if true only show self and subsites
            _datasource.StartFromCurrentNode = startAtCurrentWeb;

            treeView = new TreeView();
            treeView.ExpandDepth = levels;
            //set the datasource of the treeview and bind it
            treeView.DataSource = _datasource;

            treeView.DataBind();
      
            Controls.Add(treeView);
        }

1 comment: